Skip to content

Commit 82cb9c7

Browse files
committed
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
1 parent 3f8772c commit 82cb9c7

1 file changed

Lines changed: 21 additions & 13 deletions

File tree

sorts/quick_sort.py

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

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

1516

16-
def quick_sort(collection: list) -> list:
17+
class Comparable(Protocol):
18+
def __lt__(self, other: Any, /) -> bool: ...
19+
20+
21+
T = TypeVar("T", bound=Comparable)
22+
23+
24+
def quick_sort(collection: list[T]) -> list[T]:
1725
"""A pure Python implementation of quicksort algorithm.
1826
1927
:param collection: a mutable collection of comparable items
@@ -26,27 +34,27 @@ def quick_sort(collection: list) -> list:
2634
[]
2735
>>> quick_sort([-2, 5, 0, -45])
2836
[-45, -2, 0, 5]
37+
>>> quick_sort(["z", "a", "m", "b"])
38+
['a', 'b', 'm', 'z']
39+
>>> quick_sort([3.14, -1.0, 2.71])
40+
[-1.0, 2.71, 3.14]
41+
>>> quick_sort([0, 5, 3, 2, 2]) == sorted([0, 5, 3, 2, 2])
42+
True
43+
>>> quick_sort(["z", "a", "m"]) == sorted(["z", "a", "m"])
44+
True
2945
"""
3046
# Base case: if the collection has 0 or 1 elements, it is already sorted
3147
if len(collection) < 2:
3248
return collection
33-
34-
# Randomly select a pivot index and remove the pivot element from the collection
3549
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]
50+
pivot = collection[pivot_index]
51+
lesser = [item for item in collection if item < pivot]
52+
equal = [item for item in collection if item == pivot]
4053
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)]
54+
return [*quick_sort(lesser), *equal, *quick_sort(greater)]
4455

4556

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

0 commit comments

Comments
 (0)