File tree 1 file changed +51
-0
lines changed
1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
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 = ' ' )
You can’t perform that action at this time.
0 commit comments