Skip to content

Commit 9fc8ecb

Browse files
sorts: type exchange sort for comparable items
1 parent 927c7d3 commit 9fc8ecb

2 files changed

Lines changed: 15 additions & 2 deletions

File tree

sorts/exchange_sort.py

Lines changed: 14 additions & 2 deletions
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 Protocol
2+
3+
4+
class Comparable(Protocol):
5+
def __lt__(self, other: object, /) -> 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,7 +19,12 @@ def exchange_sort(numbers: list[int]) -> list[int]:
1219
[-2, 0, 3, 5, 10]
1320
>>> exchange_sort([])
1421
[]
15-
"""
22+
23+
>>> exchange_sort(["d", "a", "c", "b"])
24+
['a', 'b', 'c', 'd']
25+
>>> exchange_sort([2.5, -1.0, 0.0])
26+
[-1.0, 0.0, 2.5]
27+
"""
1628
numbers_length = len(numbers)
1729
for i in range(numbers_length):
1830
for j in range(i + 1, numbers_length):

tests/test_sorts.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ def test_sort_matches_builtin(sort, case):
9696
bubble_sort_iterative,
9797
bubble_sort_recursive,
9898
insertion_sort,
99+
exchange_sort,
99100
],
100101
ids=lambda f: f.__name__,
101102
)

0 commit comments

Comments
 (0)