Python Program for Iterative Merge Sort
Merge Sort is one of the most efficient sorting algorithms based on the Divide and Conquer principle. It divides an array into smaller subarrays, sorts each subarray, and then merges them to produce the final sorted array.
Unlike the recursive implementation, the iterative approach uses loops instead of function calls, which helps reduce recursion overhead and can be more memory-efficient.
How Iterative Merge Sort Works
The working of merge sort can be broken down to the following three phases:
- Divide: The array is initially treated as subarrays of size 1.
- Merge: Adjacent subarrays are merged in pairs to form sorted subarrays of size 2, then 4, 8, and so on.
- Repeat: The process continues until the entire array is merged into one sorted array.
Python Implementation
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r - m
left = arr[l:l + n1]
right = arr[m + 1:m + 1 + n2]
i = j = 0
k = l
while i < n1 and j < n2:
if left[i] <= right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
while i < n1:
arr[k] = left[i]
i += 1
k += 1
while j < n2:
arr[k] = right[j]
j += 1
k += 1
def iterativeMergeSort(arr):
n = len(arr)
curr_size = 1
while curr_size < n:
left_start = 0
while left_start < n - 1:
mid = min(left_start + curr_size - 1, n - 1)
right_end = min(left_start + 2 * curr_size - 1, n - 1)
merge(arr, left_start, mid, right_end)
left_start += 2 * curr_size
curr_size *= 2
arr = [12, 11, 13, 5, 6, 7]
print("Given array is:")
print(arr)
iterativeMergeSort(arr)
print("\nSorted array is:")
print(arr)
Output
Given array is: [12, 11, 13, 5, 6, 7] Sorted array is: [5, 6, 7, 11, 12, 13]
Explanation:
Divide
- iterativeMergeSort(): Treats the array as sorted subarrays of size 1.
- curr_size: Defines the size of subarrays to be merged in each pass.
- Bottom-up approach: Doubles curr_size in each iteration (1,2,4,8...).
- Outer loop (while curr_size < n): Runs until the array is completely merged.
Conquer
- iterativeMergeSort(): Divides the array into pairs of subarrays for merging.
- left_start: Marks the starting index of the current pair of subarrays.
- merge(): Called to combine each pair (left_start…mid and mid+1…right_end).
- left_start += 2 * curr_size: Moves to the next pair after each merge.
- curr_size *= 2: Doubles subarray size after each full pass.
Merge
- merge(): Combines two sorted subarrays into one sorted segment.
- left and right arrays: Temporary lists holding elements from both halves.
- Comparison step: Inserts smaller elements into the main array in sorted order.
- Remaining elements: Appended from whichever subarray is left.