Skip to content

Commit e7015a7

Browse files
authored
sorts: make quick_sort work with any Comparable, not just int (#15327)
* sorts: make quick_sort work with any Comparable, not just int Use a Comparable Protocol + TypeVar bound so that quick_sort correctly expresses it can sort any orderable type, not just integers. Simplifies partitioning to cleaner lesser/equal/greater lists and adds string + float doctest examples. Part of #15234 * fix: use PEP 695 type params, remove TypeVar import
1 parent 092b9d0 commit e7015a7

1 file changed

Lines changed: 18 additions & 14 deletions

File tree

‎sorts/quick_sort.py‎

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,14 @@
1111
from __future__ import annotations
1212

1313
from random import randrange
14+
from typing import Any, Protocol
1415

1516

16-
def quick_sort(collection: list) -> list:
17+
class Comparable(Protocol):
18+
def __lt__(self, other: Any, /) -> bool: ...
19+
20+
21+
def quick_sort[T: Comparable](collection: list[T]) -> list[T]:
1722
"""A pure Python implementation of quicksort algorithm.
1823
1924
:param collection: a mutable collection of comparable items
@@ -26,27 +31,26 @@ def quick_sort(collection: list) -> list:
2631
[]
2732
>>> quick_sort([-2, 5, 0, -45])
2833
[-45, -2, 0, 5]
34+
>>> quick_sort(["z", "a", "m", "b"])
35+
['a', 'b', 'm', 'z']
36+
>>> quick_sort([3.14, -1.0, 2.71])
37+
[-1.0, 2.71, 3.14]
38+
>>> quick_sort([0, 5, 3, 2, 2]) == sorted([0, 5, 3, 2, 2])
39+
True
40+
>>> quick_sort(["z", "a", "m"]) == sorted(["z", "a", "m"])
41+
True
2942
"""
30-
# Base case: if the collection has 0 or 1 elements, it is already sorted
3143
if len(collection) < 2:
3244
return collection
33-
34-
# Randomly select a pivot index and remove the pivot element from the collection
3545
pivot_index = randrange(len(collection))
36-
pivot = collection.pop(pivot_index)
37-
38-
# Partition the remaining elements into two groups: lesser or equal, and greater
39-
lesser = [item for item in collection if item <= pivot]
46+
pivot = collection[pivot_index]
47+
lesser = [item for item in collection if item < pivot]
48+
equal = [item for item in collection if item == pivot]
4049
greater = [item for item in collection if item > pivot]
41-
42-
# Recursively sort the lesser and greater groups, and combine with the pivot
43-
return [*quick_sort(lesser), pivot, *quick_sort(greater)]
50+
return [*quick_sort(lesser), *equal, *quick_sort(greater)]
4451

4552

4653
if __name__ == "__main__":
47-
# Get user input and convert it into a list of integers
4854
user_input = input("Enter numbers separated by a comma:\n").strip()
4955
unsorted = [int(item) for item in user_input.split(",")]
50-
51-
# Print the result of sorting the user-provided list
5256
print(quick_sort(unsorted))

0 commit comments

Comments
 (0)