mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-12-21 02:30:15 +00:00
bc8df6de31
* [pre-commit.ci] pre-commit autoupdate updates: - [github.com/astral-sh/ruff-pre-commit: v0.2.2 → v0.3.2](https://github.com/astral-sh/ruff-pre-commit/compare/v0.2.2...v0.3.2) - [github.com/pre-commit/mirrors-mypy: v1.8.0 → v1.9.0](https://github.com/pre-commit/mirrors-mypy/compare/v1.8.0...v1.9.0) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
53 lines
1.6 KiB
Python
53 lines
1.6 KiB
Python
"""
|
|
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
|
|
|
|
from random import randrange
|
|
|
|
|
|
def quick_sort(collection: list) -> list:
|
|
"""A pure Python implementation of quicksort algorithm.
|
|
|
|
:param collection: a mutable collection of comparable items
|
|
:return: the same collection ordered in ascending order
|
|
|
|
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]
|
|
"""
|
|
# Base case: if the collection has 0 or 1 elements, it is already sorted
|
|
if len(collection) < 2:
|
|
return collection
|
|
|
|
# Randomly select a pivot index and remove the pivot element from the collection
|
|
pivot_index = randrange(len(collection))
|
|
pivot = collection.pop(pivot_index)
|
|
|
|
# Partition the remaining elements into two groups: lesser or equal, and greater
|
|
lesser = [item for item in collection if item <= pivot]
|
|
greater = [item for item in collection if item > pivot]
|
|
|
|
# Recursively sort the lesser and greater groups, and combine with the pivot
|
|
return [*quick_sort(lesser), pivot, *quick_sort(greater)]
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# Get user input and convert it into a list of integers
|
|
user_input = input("Enter numbers separated by a comma:\n").strip()
|
|
unsorted = [int(item) for item in user_input.split(",")]
|
|
|
|
# Print the result of sorting the user-provided list
|
|
print(quick_sort(unsorted))
|