Skip to content

Instantly share code, notes, and snippets.

@mysteriousHerb
Last active May 3, 2019 07:04
Show Gist options
  • Save mysteriousHerb/3f9321fdb113587ec051e616c9e0b978 to your computer and use it in GitHub Desktop.
Save mysteriousHerb/3f9321fdb113587ec051e616c9e0b978 to your computer and use it in GitHub Desktop.
def merge(lefthalf, righthalf):
i=j=0
sorted_list = []
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
sorted_list.append(lefthalf[i])
i=i+1
else:
sorted_list.append(righthalf[j])
j=j+1
k=k+1
while i < len(lefthalf):
sorted_list.append(lefthalf[i])
i=i+1
k=k+1
while j < len(righthalf):
sorted_list.append(righthalf[j])
j=j+1
k=k+1
print('sorted list {}'.format(sorted_list))
return sorted_list
def mergeSort(nlist):
if len(nlist) <= 1:
return nlist
elif len(nlist)>1:
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
print('splitting {}, left: {}, right: {}'.format(nlist, lefthalf, righthalf))
# print("left_before sort ",lefthalf)
lefthalf = mergeSort(lefthalf)
righthalf = mergeSort(righthalf)
# print("left_after sort ",lefthalf)
return merge(lefthalf, righthalf)
nlist = [9,8,7,6,5,4,3,2]
mergeSort(nlist)
print(nlist)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment