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
21 changes: 19 additions & 2 deletions sorts/cyclic_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,28 @@ def cyclic_sort(nums: list[int]) -> list[int]:
[]
>>> cyclic_sort([3, 5, 2, 1, 4])
[1, 2, 3, 4, 5]
"""
>>> cyclic_sort([1, 2, 5])
Traceback (most recent call last):
...
ValueError: All numbers must be in range 1 to 3, got 5.

>>> cyclic_sort([7, 3, 2, 3, 54, 5, 4])
Traceback (most recent call last):
...
ValueError: All numbers must be unique, got [7, 3, 2, 3, 54, 5, 4].
"""
# Reject invalid input to prevent infinite loops and invalid indexing.
n = len(nums)
if len(set(nums)) != n:
err = f"All numbers must be unique, got {nums}."
raise ValueError(err)
for num in nums:
if not 1 <= num <= n:
err = f"All numbers must be in range 1 to {n}, got {num}."
raise ValueError(err)
# Perform cyclic sort
index = 0
while index < len(nums):
while index < n:
# Calculate the correct index for the current element
correct_index = nums[index] - 1
# If the current element is not at its correct position,
Expand Down