Skip to content

Instantly share code, notes, and snippets.

@rootVIII
Created January 15, 2020 04:04
Show Gist options
  • Save rootVIII/f8d7e5ad5508eb99af2f1695b8cbfaf7 to your computer and use it in GitHub Desktop.
Save rootVIII/f8d7e5ad5508eb99af2f1695b8cbfaf7 to your computer and use it in GitHub Desktop.
Python merge sort
#! /usr/bin/python3
# rootVIII
# merge sort
def merge(left, right):
combined, left_index, right_index = [], 0, 0
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
combined.append(left[left_index])
left_index += 1
continue
combined.append(right[right_index])
right_index += 1
combined += left[left_index:] + right[right_index:]
return combined
def merge_sort(current):
if len(current) < 2:
return current
m = int(len(current)/2)
return merge(merge_sort(current[:m]), merge_sort(current[m:]))
if __name__ == '__main__':
print(merge_sort([8, 6, 3, 0, 4, 5, 3, 9, 2]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment