Python Program for Iterative Merge Sort
Merge sort is an efficient sorting algorithm that follows the "Divide and Conquer" method to sort an array. In this tutorial, we will sort an array with help of an iterative merge sort algorithm.
Iterative Merge Sort - A basic Introduction
Merge Sort operation can also be done by an iterative method. We can also implement merge sort iteratively in a bottom-up manner.
- We start by sorting all subarrays of 1 element; then merge the result into a subarray of 2 elements
- Then merge results into a subarray of 4 elements.
- The same procedure will be followed until the array is sorted.
- The unmerged sublist element count will be isolated until the final merge call can be found out using the remainder.
- Now, the array is sorted
The below diagram will help you for understanding better:
Algorithm
As of now, we have a rough understanding of the Merge Sort operation. Let's have a look at the Algorithm followed by code for a better understanding:
- Define a function merge()
- Pass 5 parameters temp, from, to, mid, S
- Merge two sorted sublists with help of this function
- Copy remaining elements
- Copy this to reflect the original list in sorted order
- Create a function Merge_Sort()
- Iteratively sort sublist using the temporary list
- Divide the list into blocks
- The list is sorted now
- Print the resulting list
Program for Iterative Merge Sort
As discussed above in the algorithm, let us now dive into the programming part of the Iterative Merge Sort operation influenced by the algorithm.
def merge(S, temp, From, mid, to):
a = From
b = From
c = mid + 1
while b <= mid and c <= to:
if S[b] < S[c]:
temp[a] = S[b]
b = b + 1
else:
temp[a] = S[c]
c = c + 1
a = a + 1
# remaining elements
while b < len(S) and b <= mid:
temp[a] = S[b]
a = a + 1
b = b + 1
# copy back
for b in range(From, to + 1):
S[b] = temp[b]
# Iterative sort
def Merge_Sort(S):
low = 0
high = len(S) - 1
# sort list
temp = S.copy()
d = 1
while d <= high - low:
for b in range(low, high, 2*d):
From = b
mid = b + d - 1
to = min(b + 2*d - 1, high)
merge(S, temp, From, mid, to)
d = 2*d
# Iterative implementation
if __name__ == '__main__':
#driver code
S = [4, 2, 3, 1, 6, 5]
print("The Original array is: ", S)
Merge_Sort(S)
print("Array after sorting is: ", S)
The Original array is: [4, 2, 3, 1, 6, 5]
Array after sorting is: [1, 2, 3, 4, 5, 6]
Conclusion
In this tutorial, we have performed an Iterative merge sort operation in python to sort an array. The worst-case time complexity is O(n*log(n) and the space complexity is O(n).