Last active
August 29, 2015 14:05
-
-
Save fmasanori/d6aa74e1ca38888fbbfe to your computer and use it in GitHub Desktop.
mergesort
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(e, d): | |
r = [] | |
i, j = 0, 0 | |
while i < len(e) and j < len(d): | |
if e[i] <= d[j]: | |
r.append(e[i]) | |
i += 1 | |
else: | |
r.append(d[j]) | |
j += 1 | |
r += e[i:] | |
r += d[j:] | |
return r | |
def mergesort(v): | |
if len(v) <= 1: | |
return v | |
else: | |
m = len(v) // 2 | |
e = mergesort(v[:m]) | |
d = mergesort(v[m:]) | |
return merge(e, d) | |
from random import shuffle | |
v = list(range(16)) | |
shuffle(v) | |
print (v) | |
print (mergesort(v)) |
renzon
commented
Aug 28, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment