Created
March 24, 2014 05:06
-
-
Save reillyeon/9734448 to your computer and use it in GitHub Desktop.
Merge sort.
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 mergesort(a): | |
if len(a) <= 1: | |
return | |
mid = len(a) // 2 | |
b = a[:mid] | |
mergesort(b) | |
c = a[mid:] | |
mergesort(c) | |
i, j, k = 0, 0, 0 | |
while j < len(b) and k < len(c): | |
if b[j] < c[k]: | |
a[i] = b[j] | |
j += 1 | |
else: | |
a[i] = c[k] | |
k += 1 | |
i += 1 | |
while j < len(b): | |
a[i] = b[j] | |
i += 1 | |
j += 1 | |
while k < len(c): | |
a[i] = c[k] | |
i += 1 | |
k += 1 | |
if __name__ == '__main__': | |
import random | |
a = [random.randint(0, 1000) for i in range(100)] | |
print(a) | |
mergesort(a) | |
print(a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment