Saturday, September 6, 2025
HomeData Modelling & AIPython Program for Iterative Merge Sort

Python Program for Iterative Merge Sort

Following is a typical recursive implementation of Merge Sort that uses last element as pivot. Python] 

Python Program for Iterative Merge Sort

The provided Python code demonstrates the recursive implementation of the Merge Sort algorithm. Merge Sort divides an array into smaller subarrays, sorts them, and then merges them back together to achieve a sorted result. The code comprises two main functions: merge to combine two sorted arrays, and mergesort to recursively split and sort an array. The merge function compares elements from the left and right arrays, creating a sorted result array. The mergesort function repeatedly divides the array until its subarrays have one element, then merges them back. The example sorts an array using Merge Sort and prints both the original and sorted arrays, highlighting the recursive nature of the algorithm.

Python




# Recursive Python Program for merge sort
 
def merge(left, right):
    if not len(left) or not len(right):
        return left or right
 
    result = []
    i, j = 0, 0
    while (len(result) < len(left) + len(right)):
        if left[i] < right[j]:
            result.append(left[i])
            i+= 1
        else:
            result.append(right[j])
            j+= 1
        if i == len(left) or j == len(right):
            result.extend(left[i:] or right[j:])
            break
 
    return result
 
def mergesort(list):
    if len(list) < 2:
        return list
 
    middle = len(list)/2
    left = mergesort(list[:middle])
    right = mergesort(list[middle:])
 
    return merge(left, right)
     
seq = [12, 11, 13, 5, 6, 7]
print("Given array is")
print(seq);
print("\n")
print("Sorted array is")
print(mergesort(seq))
 
# Code Contributed by Mohit Gupta_OMG


Output

Given array is
[12, 11, 13, 5, 6, 7]


Sorted array is
[5, 6, 7, 11, 12, 13]

Time Complexity: O(n*log(n))
Auxiliary Space: O(n)

Please refer complete article on Iterative Merge Sort for more details!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11805 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6754 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS