Created
May 1, 2021 09:09
-
-
Save solebox/1afbcfa9ee46b1298796fd153acd7175 to your computer and use it in GitHub Desktop.
Elegant mergesort
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
def merge(L, R): | |
arr = [] | |
while len(R) and len(L): | |
left = L.pop(0) | |
right = R.pop(0) | |
if left < right: | |
arr.append(left) | |
R.insert(0, right) | |
else: | |
arr.append(right) | |
L.insert(0, left) | |
arr += L if len(L) else R | |
return arr | |
def sort(arr): | |
if len(arr) > 1: | |
mid = len(arr)//2 | |
L = sort(arr[:mid]) | |
R = sort(arr[mid:]) | |
arr = merge(L, R) | |
return arr | |
if __name__ == "__main__": | |
arr = [5, 6, 3, 2, 8, 1, 7, 4] | |
arr = sort(arr) | |
print(arr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment