Skip to content

Instantly share code, notes, and snippets.

@joubertnel
Created November 8, 2010 23:45
Show Gist options
  • Save joubertnel/668497 to your computer and use it in GitHub Desktop.
Save joubertnel/668497 to your computer and use it in GitHub Desktop.
Merge Sort
def merge(list1, list2):
result = []
index1 = index2 = 0
while index1 < len(list1) and index2 < len(list2):
key1 = list1[index1]
key2 = list2[index2]
if key1 <= key2:
result.append(key1)
index1 += 1
else:
result.append(key2)
index2 += 1
if index1 < len(list1): result += list1[index1:]
elif index2 < len(list2): result += list2[index2:]
return result
def merge_sort(keys):
if len(keys) < 2: return keys
else:
middle = len(keys)/2
list1 = keys[:middle]
list2 = keys[middle:]
sorted1 = merge_sort(list1)
sorted2 = merge_sort(list2)
return merge(sorted1, sorted2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment