Skip to content

Instantly share code, notes, and snippets.

@walac
Last active December 11, 2015 08:29
Show Gist options
  • Save walac/4573821 to your computer and use it in GitHub Desktop.
Save walac/4573821 to your computer and use it in GitHub Desktop.
A (kind of) functional implementation of the merge sort algorithm in Python.
def merge(a, b):
if not a:
return b
if not b:
return a
return a[:1] + merge(a[1:], b) if a[0] < b[0] else b[:1] + merge(a, b[1:])
def mergesort(a):
len_a = len(a)
if len_a == 1:
return a
k = len_a / 2
return merge(mergesort(a[:k]), mergesort(a[k:]))
if __name__ == '__main__':
import random
random.seed()
a = range(30)
random.shuffle(a)
print mergesort(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment