2016-07-29 20:06:49 +00:00
|
|
|
"""
|
2020-10-15 13:07:34 +00:00
|
|
|
A pure Python implementation of the quick sort algorithm
|
2016-07-29 20:06:49 +00:00
|
|
|
|
|
|
|
For doctests run following command:
|
|
|
|
python3 -m doctest -v quick_sort.py
|
|
|
|
|
|
|
|
For manual testing run:
|
2020-10-15 13:07:34 +00:00
|
|
|
python3 quick_sort.py
|
2016-07-29 20:06:49 +00:00
|
|
|
"""
|
2021-02-20 22:10:23 +00:00
|
|
|
from typing import List
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
|
2020-10-15 13:07:34 +00:00
|
|
|
def quick_sort(collection: list) -> list:
|
|
|
|
"""A pure Python implementation of quick sort algorithm
|
2016-07-29 20:06:49 +00:00
|
|
|
|
2020-10-15 13:07:34 +00:00
|
|
|
:param collection: a mutable collection of comparable items
|
2016-07-29 20:06:49 +00:00
|
|
|
:return: the same collection ordered by ascending
|
|
|
|
|
|
|
|
Examples:
|
|
|
|
>>> quick_sort([0, 5, 3, 2, 2])
|
|
|
|
[0, 2, 2, 3, 5]
|
|
|
|
>>> quick_sort([])
|
|
|
|
[]
|
2020-10-15 13:07:34 +00:00
|
|
|
>>> quick_sort([-2, 5, 0, -45])
|
|
|
|
[-45, -2, 0, 5]
|
2016-07-29 20:06:49 +00:00
|
|
|
"""
|
2020-10-15 13:07:34 +00:00
|
|
|
if len(collection) < 2:
|
2019-04-26 09:43:51 +00:00
|
|
|
return collection
|
2020-10-15 13:07:34 +00:00
|
|
|
pivot = collection.pop() # Use the last element as the first pivot
|
2021-02-20 22:10:23 +00:00
|
|
|
greater: List[int] = [] # All elements greater than pivot
|
|
|
|
lesser: List[int] = [] # All elements less than or equal to pivot
|
2020-10-15 13:07:34 +00:00
|
|
|
for element in collection:
|
|
|
|
(greater if element > pivot else lesser).append(element)
|
|
|
|
return quick_sort(lesser) + [pivot] + quick_sort(greater)
|
2016-07-29 20:06:49 +00:00
|
|
|
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
user_input = input("Enter numbers separated by a comma:\n").strip()
|
|
|
|
unsorted = [int(item) for item in user_input.split(",")]
|
|
|
|
print(quick_sort(unsorted))
|