Skip to content

Instantly share code, notes, and snippets.

@reterVision
Created January 11, 2014 13:50
Show Gist options
  • Save reterVision/739c5c6874d5eeac05e1 to your computer and use it in GitHub Desktop.
Save reterVision/739c5c6874d5eeac05e1 to your computer and use it in GitHub Desktop.
Merge Sort
"""
Merge Sort
"""
def merge(l1, l2):
if len(l1) == 0 and len(l2) == 0:
return []
if len(l1) == 0 and len(l2) != 0:
return l2[:]
if len(l1) != 0 and len(l2) == 0:
return l1[:]
if l1[0] < l2[0]:
return [l1[0]] + merge(l1[1:], l2)
else:
return [l2[0]] + merge(l1, l2[1:])
def merge_sort(l):
length = len(l)
if length <= 1:
return l
left_list = l[:length / 2]
right_list = l[length / 2:]
left_list = merge_sort(left_list)
right_list = merge_sort(right_list)
return merge(left_list, right_list)
if __name__ == "__main__":
test_list = [7, 5, 6, 3, 2, 1, 9, 8, 10]
print merge_sort(test_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment