Skip to content

Commit 3816bf4

Browse files
sorts: type cycle sort for comparable items
1 parent 927c7d3 commit 3816bf4

2 files changed

Lines changed: 14 additions & 2 deletions

File tree

sorts/cycle_sort.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,14 @@
33
Source: https://en.wikipedia.org/wiki/Cycle_sort
44
"""
55

6+
from typing import Protocol
67

7-
def cycle_sort(array: list) -> list:
8+
9+
class Comparable(Protocol):
10+
def __lt__(self, other: object, /) -> bool: ...
11+
12+
13+
def cycle_sort[T: Comparable](array: list[T]) -> list[T]:
814
"""
915
>>> cycle_sort([4, 3, 2, 1])
1016
[1, 2, 3, 4]
@@ -17,7 +23,12 @@ def cycle_sort(array: list) -> list:
1723
1824
>>> cycle_sort([])
1925
[]
20-
"""
26+
27+
>>> cycle_sort(["d", "a", "c", "b"])
28+
['a', 'b', 'c', 'd']
29+
>>> cycle_sort([2.5, -1.0, 0.0])
30+
[-1.0, 0.0, 2.5]
31+
"""
2132
array_len = len(array)
2233
for cycle_start in range(array_len - 1):
2334
item = array[cycle_start]

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+
cycle_sort,
99100
],
100101
ids=lambda f: f.__name__,
101102
)

0 commit comments

Comments
 (0)