Skip to content

Commit 1f6d8d0

Browse files
authored
Create shorting.py
1 parent da10a98 commit 1f6d8d0

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

sorting/Python/shorting.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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

0 commit comments

Comments
 (0)