Skip to content

Instantly share code, notes, and snippets.

@OzTamir
Created August 21, 2014 14:08
Show Gist options
  • Select an option

  • Save OzTamir/98e37998bbaad1d5dd82 to your computer and use it in GitHub Desktop.

Select an option

Save OzTamir/98e37998bbaad1d5dd82 to your computer and use it in GitHub Desktop.
Merge sort in Python
# merge() takes two sorted lists and merge them into one sorted list
from heapq import merge
def merge_sort(m):
''' Sort a list in O(n * log(n)) '''
# If theres only one element in the list, return the list
if len(m) <= 1:
return m
# Split the list into two equal-sized sub-lists
middle = len(m) / 2
left = m[:middle]
right = m[middle:]
# Recursivly sort each half
left = merge_sort(left)
right = merge_sort(right)
# Merge the two lists into one sorted list and return it
return list(merge(left, right))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment