Merge sort program in python

# Merge sort function which uses recursive method to divide and sort the list
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]

mergeSort(lefthalf)
print("after mergesort function of lefthalf")
mergeSort(righthalf)
print("after mergesort function of righthalf")
i=0
j=0
k=0
while i<len(lefthalf) and j<len(righthalf):
print("inside first while")
if lefthalf[i]<righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1

while i<len(lefthalf):
print("inside second while")
alist[k]=lefthalf[i]
i=i+1
k=k+1

while j<len(righthalf):
print("inside third while")
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)

# example array to be sorted
alist = [54,26,93,17,77,31,44,55,20]
# Calling mergesort function
mergeSort(alist)
# printing the sorted array
print(alist)

Leave a Reply

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