Skip to content

Commit 4dcd68e

Browse files
sorts: make exchange_sort generic for comparable items (#15304)
* sorts: make exchange_sort generic for comparable items * Ints and floats are comparable --------- Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 02716a9 commit 4dcd68e

2 files changed

Lines changed: 17 additions & 1 deletion

File tree

sorts/exchange_sort.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1-
def exchange_sort(numbers: list[int]) -> list[int]:
1+
from typing import Any, Protocol
2+
3+
4+
class Comparable(Protocol):
5+
def __lt__(self, other: Any, /) -> bool: ...
6+
7+
8+
def exchange_sort[T: Comparable](numbers: list[T]) -> list[T]:
29
"""
310
Uses exchange sort to sort a list of numbers.
411
Source: https://en.wikipedia.org/wiki/Sorting_algorithm#Exchange_sort
@@ -12,6 +19,14 @@ def exchange_sort(numbers: list[int]) -> list[int]:
1219
[-2, 0, 3, 5, 10]
1320
>>> exchange_sort([])
1421
[]
22+
>>> exchange_sort(["c", "a", "b"])
23+
['a', 'b', 'c']
24+
>>> exchange_sort([2.5, -1, 0.0])
25+
[-1, 0.0, 2.5]
26+
>>> exchange_sort([1, "a"])
27+
Traceback (most recent call last):
28+
...
29+
TypeError: '<' not supported between instances of 'str' and 'int'
1530
"""
1631
numbers_length = len(numbers)
1732
for i in range(numbers_length):

tests/test_sorts.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ def test_sort_matches_builtin(sort, case) -> None:
117117
circle_sort,
118118
cocktail_shaker_sort,
119119
comb_sort,
120+
exchange_sort,
120121
gnome_sort,
121122
insertion_sort,
122123
merge_sort,

0 commit comments

Comments
 (0)