Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion sorts/cycle_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,14 @@
Source: https://en.wikipedia.org/wiki/Cycle_sort
"""

from typing import Any, Protocol

def cycle_sort(array: list) -> list:

class Comparable(Protocol):
def __lt__(self, other: Any, /) -> bool: ...


def cycle_sort[T: Comparable](array: list[T]) -> list[T]:
"""
>>> cycle_sort([4, 3, 2, 1])
[1, 2, 3, 4]
Expand All @@ -15,6 +21,14 @@ def cycle_sort(array: list) -> list:
>>> cycle_sort([-.1, -.2, 1.3, -.8])
[-0.8, -0.2, -0.1, 1.3]

>>> cycle_sort(["c", "a", "b"])
['a', 'b', 'c']

>>> cycle_sort([1, "a"])
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'

>>> cycle_sort([])
[]
"""
Expand Down
1 change: 1 addition & 0 deletions tests/test_sorts.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ def test_sort_matches_builtin(sort, case) -> None:
circle_sort,
cocktail_shaker_sort,
comb_sort,
cycle_sort,
exchange_sort,
gnome_sort,
insertion_sort,
Expand Down
Loading