Python Program for Iterative Merge Sort

Created with Sketch.

Python Program for Iterative Merge Sort

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


# 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]:
            i+= 1
            j+= 1
        if i == len(left) or j == len(right):
            result.extend(left[i:] or right[j:])
    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("Sorted array is")

Leave a Reply

Your email address will not be published. Required fields are marked *