77python3 -m doctest -v cyclic_sort.py
88For manual testing run:
99python cyclic_sort.py
10+ or
11+ python3 cyclic_sort.py
1012"""
1113
1214
13- def cyclic_sort (nums : list ) -> list :
15+ def cyclic_sort (nums : list [ int ] ) -> list [ int ] :
1416 """
1517 Sorts the input list in-place using the Cyclic Sort algorithm.
1618
@@ -20,25 +22,25 @@ def cyclic_sort(nums: list) -> list:
2022 Time complexity: O(n), where n is the number of elements in the list.
2123
2224 Examples:
23- >>> cyclic_sort([3, 5, 2, 1, 4])
24- [1, 2, 3, 4, 5]
2525 >>> cyclic_sort([])
2626 []
27+ >>> cyclic_sort([3, 5, 2, 1, 4])
28+ [1, 2, 3, 4, 5]
2729 """
2830
2931 # Perform cyclic sort
30- i = 0
31- while i < len (nums ):
32+ index = 0
33+ while index < len (nums ):
3234 # Calculate the correct index for the current element
33- correct_index = nums [i ] - 1
35+ correct_index = nums [index ] - 1
3436 # If the current element is not at its correct position,
3537 # swap it with the element at its correct index
36- if nums [ i ] != nums [ correct_index ] :
37- nums [i ], nums [correct_index ] = nums [correct_index ], nums [i ]
38+ if index != correct_index :
39+ nums [index ], nums [correct_index ] = nums [correct_index ], nums [index ]
3840 else :
3941 # If the current element is already in its correct position,
4042 # move to the next element
41- i += 1
43+ index += 1
4244
4345 return nums
4446
0 commit comments