Skip to content

Instantly share code, notes, and snippets.

@smahs
Created June 28, 2018 09:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save smahs/daaebe6620ab0b1d410ea62e2d6fe40a to your computer and use it in GitHub Desktop.
Save smahs/daaebe6620ab0b1d410ea62e2d6fe40a to your computer and use it in GitHub Desktop.
Merge Sort - the Pythonic way
def sort(l):
if len(l) <= 1:
return l
mid = len(l) // 2
return merge(sort(l[:mid]), sort(l[mid:]))
def merge(l, r):
out = []
while l and r:
if l[0] <= r[0]:
out.append(l.pop(0))
else:
out.append(r.pop(0))
out.extend(l)
out.extend(r)
return out
def main():
l = [3, 2, 5, 1, 4]
print(sort(l))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment