diff --git a/sorts/cycle_sort.py b/sorts/cycle_sort.py index 7177c8ea110d..bc8a7531097f 100644 --- a/sorts/cycle_sort.py +++ b/sorts/cycle_sort.py @@ -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] @@ -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([]) [] """ diff --git a/tests/test_sorts.py b/tests/test_sorts.py index 2c9b79aa4bfe..1631a47fcf84 100644 --- a/tests/test_sorts.py +++ b/tests/test_sorts.py @@ -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,