Skip to content

Commit ac1a40f

Browse files
sorts: make cycle sort support comparable items
1 parent 12d0648 commit ac1a40f

1 file changed

Lines changed: 19 additions & 5 deletions

File tree

sorts/cycle_sort.py

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,26 +3,38 @@
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]
11-
1217
>>> cycle_sort([-4, 20, 0, -50, 100, -1])
1318
[-50, -4, -1, 0, 20, 100]
14-
1519
>>> cycle_sort([-.1, -.2, 1.3, -.8])
1620
[-0.8, -0.2, -0.1, 1.3]
17-
1821
>>> cycle_sort([])
1922
[]
23+
>>> cycle_sort(["banana", "apple", "cherry"])
24+
['apple', 'banana', 'cherry']
25+
>>> cycle_sort([3.14, 1.5, 2.7])
26+
[1.5, 2.7, 3.14]
27+
>>> cycle_sort([1, "two"]) # doctest: +ELLIPSIS
28+
Traceback (most recent call last):
29+
...
30+
TypeError: ...
2031
"""
2132
array_len = len(array)
33+
2234
for cycle_start in range(array_len - 1):
2335
item = array[cycle_start]
24-
2536
pos = cycle_start
37+
2638
for i in range(cycle_start + 1, array_len):
2739
if array[i] < item:
2840
pos += 1
@@ -34,8 +46,10 @@ def cycle_sort(array: list) -> list:
3446
pos += 1
3547

3648
array[pos], item = item, array[pos]
49+
3750
while pos != cycle_start:
3851
pos = cycle_start
52+
3953
for i in range(cycle_start + 1, array_len):
4054
if array[i] < item:
4155
pos += 1

0 commit comments

Comments
 (0)