Skip to content
Open
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
24 changes: 19 additions & 5 deletions sorts/cycle_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
Loading