Skip to content

Instantly share code, notes, and snippets.

@multivac61
Created October 3, 2015 14:10
Show Gist options
  • Save multivac61/426262cb4897fd621316 to your computer and use it in GitHub Desktop.
Save multivac61/426262cb4897fd621316 to your computer and use it in GitHub Desktop.
A simple implementation of merge sort in Python.
def merge_sort(m, sort_by):
def merge(left, right):
result = []
while left and right:
# keep on merging/sorting from left/right
# lists on an element basis
if sort_by(left[0], right[0]):
result.append(left[0])
left.pop(0)
else:
result.append(right[0])
right.pop(0)
# there might be elements left in left/right list
for i in left:
result.append(i)
for i in right:
result.append(i)
return result
if len(m) <= 1: # if list less than one element return
return m
middle = len(m) / 2 # split list in half
left = m[:middle]; right = m[middle:]
left = merge_sort(left, max_order) # sort left
right = merge_sort(right, max_order) # sort right
return merge(left, right) # merge together sorted left/right
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment