Skip to content

Commit 4d3f060

Browse files
authored
Merge pull request #38 from Aviral1-jain/patch-6
Create cycleSort.py
2 parents ffd4f8d + 5011489 commit 4d3f060

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

Python/sorting/cycleSort.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
41+
42+
# driver code
43+
arr = [1, 8, 3, 9, 10, 10, 2, 4]
44+
n = len(arr)
45+
cycleSort(arr)
46+
47+
print("After sort : ")
48+
for i in range(0, n):
49+
print(arr[i], end=' ')

0 commit comments

Comments
 (0)