From ac1a40f719eff215addeef70a8a0d28920b98c01 Mon Sep 17 00:00:00 2001 From: Ashwin121425-R Date: Sat, 12 Sep 2026 15:29:53 +0530 Subject: [PATCH] sorts: make cycle sort support comparable items --- sorts/cycle_sort.py | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/sorts/cycle_sort.py b/sorts/cycle_sort.py index 7177c8ea110d..24891a74582b 100644 --- a/sorts/cycle_sort.py +++ b/sorts/cycle_sort.py @@ -3,26 +3,38 @@ 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] - >>> cycle_sort([-4, 20, 0, -50, 100, -1]) [-50, -4, -1, 0, 20, 100] - >>> cycle_sort([-.1, -.2, 1.3, -.8]) [-0.8, -0.2, -0.1, 1.3] - >>> cycle_sort([]) [] + >>> cycle_sort(["banana", "apple", "cherry"]) + ['apple', 'banana', 'cherry'] + >>> cycle_sort([3.14, 1.5, 2.7]) + [1.5, 2.7, 3.14] + >>> cycle_sort([1, "two"]) # doctest: +ELLIPSIS + Traceback (most recent call last): + ... + TypeError: ... """ array_len = len(array) + for cycle_start in range(array_len - 1): item = array[cycle_start] - pos = cycle_start + for i in range(cycle_start + 1, array_len): if array[i] < item: pos += 1 @@ -34,8 +46,10 @@ def cycle_sort(array: list) -> list: pos += 1 array[pos], item = item, array[pos] + while pos != cycle_start: pos = cycle_start + for i in range(cycle_start + 1, array_len): if array[i] < item: pos += 1