From 3816bf425221c650f94c3cc0163c97c20142b624 Mon Sep 17 00:00:00 2001 From: Harsh Raj Singhania <40535627+HarshRajSinghania@users.noreply.github.com> Date: Thu, 10 Sep 2026 00:09:40 +0530 Subject: [PATCH] sorts: type cycle sort for comparable items --- sorts/cycle_sort.py | 15 +++++++++++++-- tests/test_sorts.py | 1 + 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/sorts/cycle_sort.py b/sorts/cycle_sort.py index 7177c8ea110d..1e3e5b2426f9 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 Protocol -def cycle_sort(array: list) -> list: + +class Comparable(Protocol): + def __lt__(self, other: object, /) -> bool: ... + + +def cycle_sort[T: Comparable](array: list[T]) -> list[T]: """ >>> cycle_sort([4, 3, 2, 1]) [1, 2, 3, 4] @@ -17,7 +23,12 @@ def cycle_sort(array: list) -> list: >>> cycle_sort([]) [] - """ + + >>> cycle_sort(["d", "a", "c", "b"]) + ['a', 'b', 'c', 'd'] + >>> cycle_sort([2.5, -1.0, 0.0]) + [-1.0, 0.0, 2.5] +""" array_len = len(array) for cycle_start in range(array_len - 1): item = array[cycle_start] diff --git a/tests/test_sorts.py b/tests/test_sorts.py index caa4b31cac81..99ef3eb1e20e 100644 --- a/tests/test_sorts.py +++ b/tests/test_sorts.py @@ -96,6 +96,7 @@ def test_sort_matches_builtin(sort, case): bubble_sort_iterative, bubble_sort_recursive, insertion_sort, + cycle_sort, ], ids=lambda f: f.__name__, )