Skip to content

Instantly share code, notes, and snippets.

@scientificRat
Created October 17, 2018 06:33
Show Gist options
  • Save scientificRat/835e5ad2c9a2196da31c8af1491aee2a to your computer and use it in GitHub Desktop.
Save scientificRat/835e5ad2c9a2196da31c8af1491aee2a to your computer and use it in GitHub Desktop.
merge_sort implementation in python
def merge_sort(array):
if len(array) == 1:
return [array[0]]
elif len(array) == 2:
if array[0] > array[1]:
return [array[1], array[0]]
return [array[0], array[1]]
mid = len(array) // 2
left = merge_sort(array[0:mid])
right = merge_sort(array[mid:])
# merge
out = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
while i < len(left):
out.append(left[i])
i += 1
while j < len(right):
out.append(right[j])
j += 1
return out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment