7
7
python3 -m doctest -v cyclic_sort.py
8
8
For manual testing run:
9
9
python cyclic_sort.py
10
+ or
11
+ python3 cyclic_sort.py
10
12
"""
11
13
12
14
13
- def cyclic_sort (nums : list ) -> list :
15
+ def cyclic_sort (nums : list [ int ] ) -> list [ int ] :
14
16
"""
15
17
Sorts the input list in-place using the Cyclic Sort algorithm.
16
18
@@ -20,25 +22,25 @@ def cyclic_sort(nums: list) -> list:
20
22
Time complexity: O(n), where n is the number of elements in the list.
21
23
22
24
Examples:
23
- >>> cyclic_sort([3, 5, 2, 1, 4])
24
- [1, 2, 3, 4, 5]
25
25
>>> cyclic_sort([])
26
26
[]
27
+ >>> cyclic_sort([3, 5, 2, 1, 4])
28
+ [1, 2, 3, 4, 5]
27
29
"""
28
30
29
31
# Perform cyclic sort
30
- i = 0
31
- while i < len (nums ):
32
+ index = 0
33
+ while index < len (nums ):
32
34
# Calculate the correct index for the current element
33
- correct_index = nums [i ] - 1
35
+ correct_index = nums [index ] - 1
34
36
# If the current element is not at its correct position,
35
37
# 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 ]
38
40
else :
39
41
# If the current element is already in its correct position,
40
42
# move to the next element
41
- i += 1
43
+ index += 1
42
44
43
45
return nums
44
46
0 commit comments