Last active
December 11, 2015 08:29
-
-
Save walac/4573821 to your computer and use it in GitHub Desktop.
A (kind of) functional implementation of the merge sort algorithm 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
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