Skip to content

Commit 50bbd38

Browse files
authored
Create Cycle_Sort.py
1 parent a328b66 commit 50bbd38

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
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 # keeps track of the number of writes or swaps made during the sorting process
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+
position = cycleStart
10+
for i in range(cycleStart + 1, len(array)):
11+
if array[i] < item:
12+
position += 1
13+
14+
# If the item is already there, this is not a cycle.
15+
if position == cycleStart:
16+
continue
17+
18+
# Otherwise, put the item there or right after any duplicates.
19+
while item == array[position]:
20+
position += 1
21+
array[position], item = item, array[position]
22+
writes += 1
23+
24+
# Rotate the rest of the cycle.
25+
while position != cycleStart:
26+
27+
# Find where to put the item.
28+
position = cycleStart
29+
for i in range(cycleStart + 1, len(array)):
30+
if array[i] < item:
31+
position += 1
32+
33+
# Put the item there or right after any duplicates.
34+
while item == array[position]:
35+
position += 1
36+
array[position], item = item, array[position]
37+
writes += 1
38+
39+
return writes
40+
41+
42+
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)