Skip to content

Commit cfc9075

Browse files
Make quick sort support comparable items
1 parent d502013 commit cfc9075

1 file changed

Lines changed: 18 additions & 5 deletions

File tree

sorts/quick_sort.py

Lines changed: 18 additions & 5 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 Protocol
1415

1516

16-
def quick_sort(collection: list) -> list:
17+
class Comparable(Protocol):
18+
def __lt__(self, other: object, /) -> 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,18 +31,26 @@ def quick_sort(collection: list) -> list:
2631
[]
2732
>>> quick_sort([-2, 5, 0, -45])
2833
[-45, -2, 0, 5]
34+
>>> quick_sort(["banana", "apple", "cherry"])
35+
['apple', 'banana', 'cherry']
36+
>>> quick_sort([3.14, 1.5, 2.7])
37+
[1.5, 2.7, 3.14]
38+
>>> quick_sort([1, "two"]) # doctest: +ELLIPSIS
39+
Traceback (most recent call last):
40+
...
41+
TypeError: '<' not supported between instances of ...
2942
"""
3043
# Base case: if the collection has 0 or 1 elements, it is already sorted
3144
if len(collection) < 2:
3245
return collection
3346

34-
# Randomly select a pivot index and remove the pivot element from the collection
47+
# Randomly select a pivot index and remove the pivot element
3548
pivot_index = randrange(len(collection))
3649
pivot = collection.pop(pivot_index)
3750

38-
# Partition the remaining elements into two groups: lesser or equal, and greater
39-
lesser = [item for item in collection if item <= pivot]
40-
greater = [item for item in collection if item > pivot]
51+
# Partition the remaining elements using the less-than comparison
52+
lesser = [item for item in collection if item < pivot]
53+
greater = [item for item in collection if not item < pivot]
4154

4255
# Recursively sort the lesser and greater groups, and combine with the pivot
4356
return [*quick_sort(lesser), pivot, *quick_sort(greater)]

0 commit comments

Comments
 (0)