Skip to content

Instantly share code, notes, and snippets.

@solebox
Created May 1, 2021 09:09
Show Gist options
  • Save solebox/1afbcfa9ee46b1298796fd153acd7175 to your computer and use it in GitHub Desktop.
Save solebox/1afbcfa9ee46b1298796fd153acd7175 to your computer and use it in GitHub Desktop.
Elegant mergesort
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