Here is how to sort using Merge Sort method in Python.
Run the code here: https://repl.it/@VinitKhandelwal/merge-sort
Run the code here: https://repl.it/@VinitKhandelwal/merge-sort
#mergeSort function to break lists into halves
def mergeSort(list1):
# if list size is just 1 then no sorting required
length = len(list1)
if length < 2:
return list1
# cutting lists into middle
middle = int(length/2)
left = list1[0:middle]
right = list1[middle:]
#first mergeSort until splitted completely, then merge
return merge(mergeSort(left),mergeSort(right))
# merge function to merge back all splitted lists
def merge(left, right):
result = []
leftIndex = 0
rightIndex = 0
# compare and merge
while leftIndex < len(left) and rightIndex < len(right):
if left[leftIndex] < right[rightIndex]:
result.append(left[leftIndex])
leftIndex += 1
else:
result.append(right[rightIndex])
rightIndex += 1
#merge remaining
return result + left[leftIndex:] + right[rightIndex:]
print(mergeSort([6,4,2,8,7,1,3,0,9,5]))
Comments
Post a Comment