Created
February 16, 2016 14:19
-
-
Save gurunars/18dac661c5fb9a9d3267 to your computer and use it in GitHub Desktop.
Merge sort in 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
import random | |
my_randoms = random.sample(xrange(100), 13) | |
def merge(first_half, second_half): | |
if len(first_half) == 0: | |
return second_half | |
elif len(second_half) == 0: | |
return first_half | |
elif first_half[0] < second_half[0]: | |
return [first_half[0]] + merge(first_half[1:], second_half) | |
else: | |
return [second_half[0]] + merge(first_half, second_half[1:]) | |
# Average: O(n log(n)) | |
def merge_sort(items): | |
if len(items) < 2: | |
return items | |
else: | |
pivot_point = len(items) / 2 | |
return merge( | |
merge_sort(items[:pivot_point]), | |
merge_sort(items[pivot_point:])) | |
print merge_sort(my_randoms) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment