Last active
October 13, 2019 11:27
-
-
Save MarshalX/8f5cbfb99a3a2d17f7055ccd561d6fbc to your computer and use it in GitHub Desktop.
Merge Sort on Python
This file contains hidden or 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
import random | |
def merge_sort(a): | |
n = len(a) | |
if n < 2: | |
return a | |
l = merge_sort(a[:n//2]) | |
r = merge_sort(a[n//2:n]) | |
i = j = 0 | |
res = [] | |
while i < len(l) or j < len(r): | |
if not i < len(l): | |
res.append(r[j]) | |
j += 1 | |
elif not j < len(r): | |
res.append(l[i]) | |
i += 1 | |
elif l[i] < r[j]: | |
res.append(l[i]) | |
i += 1 | |
else: | |
res.append(r[j]) | |
j += 1 | |
return res | |
if __name__ == '__main__': | |
A = [random.randint(0, 10) for i in range(10)] | |
print(A) | |
A = merge_sort(A) | |
print(A) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment