Skip to content

Commit ac33016

Browse files
authored
Merge pull request TheAlgorithms#199 from honeycoder96/patch-1
Create cyclesort.py
2 parents 92bf7a6 + 8c5fd4b commit ac33016

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

sorts/cyclesort.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Code contributed by Honey Sharma
2+
def cycle_sort(array):
3+
ans = 0
4+
5+
# Pass through the array to find cycles to rotate.
6+
for cycleStart in range(0, len(array) - 1):
7+
item = array[cycleStart]
8+
9+
# finding the position for putting the item.
10+
pos = cycleStart
11+
for i in range(cycleStart + 1, len(array)):
12+
if array[i] < item:
13+
pos += 1
14+
15+
# If the item is already present-not a cycle.
16+
if pos == cycleStart:
17+
continue
18+
19+
# Otherwise, put the item there or right after any duplicates.
20+
while item == array[pos]:
21+
pos += 1
22+
array[pos], item = item, array[pos]
23+
ans += 1
24+
25+
# Rotate the rest of the cycle.
26+
while pos != cycleStart:
27+
28+
# Find where to put the item.
29+
pos = cycleStart
30+
for i in range(cycleStart + 1, len(array)):
31+
if array[i] < item:
32+
pos += 1
33+
34+
# Put the item there or right after any duplicates.
35+
while item == array[pos]:
36+
pos += 1
37+
array[pos], item = item, array[pos]
38+
ans += 1
39+
40+
return ans
41+
42+
43+
# Main Code starts here
44+
user_input = input('Enter numbers separated by a comma:\n')
45+
unsorted = [int(item) for item in user_input.split(',')]
46+
n = len(unsorted)
47+
cycle_sort(unsorted)
48+
49+
print("After sort : ")
50+
for i in range(0, n):
51+
print(unsorted[i], end=' ')

0 commit comments

Comments
 (0)