Created
May 29, 2011 15:55
-
-
Save gennad/997885 to your computer and use it in GitHub Desktop.
Mergesort Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Merges two sorted lists into one sorted list. recursively | |
def merge(left, right): | |
if len(left) == 0 and len(right) == 0: | |
return [] | |
elif len(left) == 0: | |
return right | |
elif len(right) == 0: | |
return left | |
else: | |
if left[0] <= right[0]: | |
return left[:1] + merge(left[1:],right) | |
else: | |
return right[:1] + merge(left,right[1:]) | |
#Splits a list in half and returns the halves | |
def halve(list): | |
return list[:len(list)//2],list[len(list)//2:] | |
#Mergesort | |
def mergesort(list): | |
if len(list) <= 1: | |
return list | |
left,right = halve(list) | |
left,right = mergesort(left),mergesort(right) | |
return merge(left,right) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment