Skip to content

Instantly share code, notes, and snippets.

@sneeu
Created April 27, 2011 18:06
Show Gist options
  • Save sneeu/944805 to your computer and use it in GitHub Desktop.
Save sneeu/944805 to your computer and use it in GitHub Desktop.
Quick sort in Python.
def qsort(l):
"""
>>> qsort([])
[]
>>> qsort([-1])
[-1]
>>> qsort([1, 2, 3, 4])
[1, 2, 3, 4]
>>> qsort([4, 3, 2, 1])
[1, 2, 3, 4]
>>> qsort([5, 2, 7, 1, 3, 10, 8])
[1, 2, 3, 5, 7, 8, 10]
"""
if len(l) < 2:
return l
h, t = l[0], l[1:]
return qsort([u for u in t if u < h]) + [h] + qsort([u for u in t if u >= h])
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment