Program for Recursive Merge Sort using Python

Introduction

In previous article we understood the python code for merge sort. Now we will understand the recursive implementation of merge sort.

The last element in the given array is treated as the pivot element

Program

def merge_arr(left, right):
    if not len(left) or not len(right):
        return left or right
    output = []
    x , y = 0, 0
    while (len(output) < len(left) + len(right)):
        if left[x] < right[y]:
            output.append(left[x])
            x += 1
        else:
            output.append(right[y])
            y += 1
        if x == len(left) or y == len(right):
            output.extend(left[x:] or right[y:])
            break
    return output


def sort(arr):
    if len(arr) < 2:
        return arr
    mid = int(len(arr)/2)
    left = sort(arr[:mid])
    right = sort(arr[mid:])
    return merge_arr(left, right)
       
ip_arr = [12, 11, 13, 5, 6, 7]
print("The sorted array is :")
print(sort(ip_arr))

Output

Program for Recursive Merge Sort using Python

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.