Skip to content

Instantly share code, notes, and snippets.

@jatinsharrma
Created July 26, 2019 10:39
Show Gist options
  • Save jatinsharrma/d5c26fd334660f4bab070e04ce689f95 to your computer and use it in GitHub Desktop.
Save jatinsharrma/d5c26fd334660f4bab070e04ce689f95 to your computer and use it in GitHub Desktop.
Merge Sort
'''-------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------MERGE SORT-------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------'''
def merge_sort(unsorted_list):
if len(unsorted_list) == 1:
return unsorted_list
mid = len(unsorted_list)//2
right = unsorted_list[mid:]
left = unsorted_list[:mid]
right = merge_sort(right)
left = merge_sort(left)
return merge(right, left)
def merge(right, left):
res= []
while len(right) != 0 and len(left) != 0:
if right[0] > left[0]:
res.append(left[0])
left.remove(left[0])
else:
res.append(right[0])
right.remove(right[0])
if len(right) == 0:
res= res + left
else:
res = res + right
return res
unsorted_list = [9,8,7,6,5,4,3,2,1]
print(merge_sort(unsorted_list))
'''///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
----------------------------------COMPLEXITY = O(n*log(n))[Worst case] / O(n*log(n))[Best Case]----------------------------
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment