Created
November 15, 2012 01:54
-
-
Save syohex/4076158 to your computer and use it in GitHub Desktop.
Merge sort implementation in Python
This file contains hidden or 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
#!/usr/bin/env python | |
# -*- coding:utf-8 -*- | |
import random | |
def merge_sort(nums): | |
if len(nums) <= 1: | |
return nums | |
else: | |
b, c = split(nums) | |
return merge(merge_sort(b), merge_sort(c)) | |
def split(a): | |
if len(a) <= 1: | |
return a, [] | |
else: | |
half_index = len(a) / 2 | |
return a[0:half_index], a[half_index:] | |
def merge(a, b): | |
retval = [] | |
while len(a) != 0 and len(b) != 0: | |
if a[0] < b[0]: | |
retval.append(a[0]) | |
a.pop(0) | |
else: | |
retval.append(b[0]) | |
b.pop(0) | |
if len(a) > 0: | |
retval.extend(a) | |
elif len(b) > 0: | |
retval.extend(b) | |
return retval | |
if __name__ == "__main__": | |
nums = [random.randint(0, 1000) for x in range(30)] | |
print merge_sort(nums) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment