Skip to content

Instantly share code, notes, and snippets.

@syohex
Created November 15, 2012 01:54
Show Gist options
  • Save syohex/4076158 to your computer and use it in GitHub Desktop.
Save syohex/4076158 to your computer and use it in GitHub Desktop.
Merge sort implementation in Python
#!/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