Skip to content

Instantly share code, notes, and snippets.

@erika-dike
Created July 3, 2018 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erika-dike/5eb10230cbf229b26a52a9d1df8ed490 to your computer and use it in GitHub Desktop.
Save erika-dike/5eb10230cbf229b26a52a9d1df8ed490 to your computer and use it in GitHub Desktop.
def merge_sort(alist):
if len(alist) > 1:
mid = len(alist) // 2
lefthalf = alist[:mid]
righthalf = alist[mid:]
merge_sort(lefthalf)
merge_sort(righthalf)
i = j = k = 0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k] = lefthalf[i]
i += 1
else:
alist[k] = righthalf[j]
j += 1
k += 1
while i < len(lefthalf):
alist[k] = lefthalf[i]
i += 1
k += 1
while j < len(righthalf):
alist[k] = righthalf[j]
j += 1
k += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment