Python/sorts/quick_sort.py

49 lines
1.4 KiB
Python
Raw Normal View History

"""
A pure Python implementation of the quick sort algorithm
For doctests run following command:
python3 -m doctest -v quick_sort.py
For manual testing run:
python3 quick_sort.py
"""
from __future__ import annotations
2019-10-05 05:14:13 +00:00
from random import randrange
2019-10-05 05:14:13 +00:00
def quick_sort(collection: list) -> list:
"""A pure Python implementation of quick sort algorithm
:param collection: a mutable collection of comparable items
:return: the same collection ordered by ascending
Examples:
>>> quick_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> quick_sort([])
[]
>>> quick_sort([-2, 5, 0, -45])
[-45, -2, 0, 5]
"""
if len(collection) < 2:
return collection
pivot_index = randrange(len(collection)) # Use random element as pivot
pivot = collection[pivot_index]
greater: list[int] = [] # All elements greater than pivot
lesser: list[int] = [] # All elements less than or equal to pivot
for element in collection[:pivot_index]:
(greater if element > pivot else lesser).append(element)
for element in collection[pivot_index + 1 :]:
(greater if element > pivot else lesser).append(element)
return [*quick_sort(lesser), pivot, *quick_sort(greater)]
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))