Skip to content

Instantly share code, notes, and snippets.

@akun
Last active March 30, 2017 05:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akun/d90998068f4e1f3eb169 to your computer and use it in GitHub Desktop.
Save akun/d90998068f4e1f3eb169 to your computer and use it in GitHub Desktop.
quick sort(easy way, but more memory)
#!/urs/bin/env python
def qsort(alist):
"""
quick sort(easy way, but more memory)
test: python -m doctest qsort.py
>>> import math
>>> import random
>>> size = 100
>>> alist = [random.randint(0, size * 10) for i in range(size)]
>>> qlist = qsort(alist)
>>> alist.sort()
>>> assert qlist == alist
"""
if len(alist) <= 1:
return alist
key = alist[0]
left_list, middle_list, right_list = [], [], []
[{i < key: left_list, i == key: middle_list, i > key: right_list}[
True
].append(i) for i in alist]
return qsort(left_list) + middle_list + qsort(right_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment