diff --git a/sorts/cyclic_sort.py b/sorts/cyclic_sort.py index 9e81291548d4..554cafb14917 100644 --- a/sorts/cyclic_sort.py +++ b/sorts/cyclic_sort.py @@ -5,6 +5,7 @@ python -m doctest -v cyclic_sort.py or python3 -m doctest -v cyclic_sort.py + For manual testing run: python cyclic_sort.py or @@ -29,18 +30,32 @@ def cyclic_sort(nums: list[int]) -> list[int]: [1, 2, 3, 4, 5] """ + # Input validation + seen = set() + n = len(nums) + + for num in nums: + if num in seen: + message = f"All numbers must be unique, got {nums}" + raise ValueError(message) + + if num < 1 or num > n: + message = f"All numbers must be in range 1 to {n}, got {num}" + raise ValueError(message) + + seen.add(num) + # Perform cyclic sort index = 0 while index < len(nums): - # Calculate the correct index for the current element correct_index = nums[index] - 1 - # If the current element is not at its correct position, - # swap it with the element at its correct index + if index != correct_index: - nums[index], nums[correct_index] = nums[correct_index], nums[index] + nums[index], nums[correct_index] = ( + nums[correct_index], + nums[index], + ) else: - # If the current element is already in its correct position, - # move to the next element index += 1 return nums @@ -50,6 +65,7 @@ def cyclic_sort(nums: list[int]) -> list[int]: import doctest doctest.testmod() + user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(*cyclic_sort(unsorted), sep=",")