@@ -18,42 +18,32 @@ def cycle_sort(array: list) -> list:
18
18
>>> cycle_sort([])
19
19
[]
20
20
"""
21
- ans = 0
21
+ array_len = len (array )
22
+ for cycle_start in range (0 , array_len - 1 ):
23
+ item = array [cycle_start ]
22
24
23
- # Pass through the array to find cycles to rotate.
24
- for cycleStart in range (0 , len (array ) - 1 ):
25
- item = array [cycleStart ]
26
-
27
- # finding the position for putting the item.
28
- pos = cycleStart
29
- for i in range (cycleStart + 1 , len (array )):
25
+ pos = cycle_start
26
+ for i in range (cycle_start + 1 , array_len ):
30
27
if array [i ] < item :
31
28
pos += 1
32
29
33
- # If the item is already present-not a cycle.
34
- if pos == cycleStart :
30
+ if pos == cycle_start :
35
31
continue
36
32
37
- # Otherwise, put the item there or right after any duplicates.
38
33
while item == array [pos ]:
39
34
pos += 1
40
- array [pos ], item = item , array [pos ]
41
- ans += 1
42
-
43
- # Rotate the rest of the cycle.
44
- while pos != cycleStart :
45
35
46
- # Find where to put the item.
47
- pos = cycleStart
48
- for i in range (cycleStart + 1 , len (array )):
36
+ array [pos ], item = item , array [pos ]
37
+ while pos != cycle_start :
38
+ pos = cycle_start
39
+ for i in range (cycle_start + 1 , array_len ):
49
40
if array [i ] < item :
50
41
pos += 1
51
42
52
- # Put the item there or right after any duplicates.
53
43
while item == array [pos ]:
54
44
pos += 1
45
+
55
46
array [pos ], item = item , array [pos ]
56
- ans += 1
57
47
58
48
return array
59
49
0 commit comments