File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ def cycleSort(array):
2+ writes = 0
3+
4+ # Loop through the array to find cycles to rotate.
5+ for cycleStart in range(0, len(array) - 1):
6+ item = array[cycleStart]
7+
8+ # Find where to put the item.
9+ pos = cycleStart
10+ for i in range(cycleStart + 1, len(array)):
11+ if array[i] < item:
12+ pos += 1
13+
14+ # If the item is already there, this is not a cycle.
15+ if pos == cycleStart:
16+ continue
17+
18+ # Otherwise, put the item there or right after any duplicates.
19+ while item == array[pos]:
20+ pos += 1
21+ array[pos], item = item, array[pos]
22+ writes += 1
23+
24+ # Rotate the rest of the cycle.
25+ while pos != cycleStart:
26+
27+ # Find where to put the item.
28+ pos = cycleStart
29+ for i in range(cycleStart + 1, len(array)):
30+ if array[i] < item:
31+ pos += 1
32+
33+ # Put the item there or right after any duplicates.
34+ while item == array[pos]:
35+ pos += 1
36+ array[pos], item = item, array[pos]
37+ writes += 1
38+
39+ return writes
40+
You can’t perform that action at this time.
0 commit comments