Skip to content

Commit f9d3ad0

Browse files
authored
Merge pull request deutranium#170 from vczoika/ruby-cyclesort
Added Ruby Cycle Sort
2 parents 60087f4 + 92377d9 commit f9d3ad0

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

sortingAlgo/cycleSort/cycleSort.rb

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
def cycle_sort(array, swaps)
2+
swaps = 0
3+
cycle_start = 0
4+
5+
while cycle_start < array.length - 1
6+
number_to_swap = array[cycle_start]
7+
position = cycle_start
8+
9+
i = cycle_start + 1
10+
while i < array.length
11+
if array[i] < number_to_swap
12+
position += 1
13+
end
14+
i += 1
15+
end
16+
17+
if position != cycle_start
18+
while number_to_swap == array[position]
19+
position += 1
20+
end
21+
22+
array[position], number_to_swap = number_to_swap, array[position]
23+
swaps += 1
24+
end
25+
26+
while position != cycle_start
27+
position = cycle_start
28+
29+
j = cycle_start + 1
30+
while j < array.length - 1
31+
if array[j] < number_to_swap
32+
position += 1
33+
end
34+
35+
while number_to_swap == array[position]
36+
position += 1
37+
end
38+
39+
j += 1
40+
end
41+
42+
array[position], number_to_swap = number_to_swap, array[position]
43+
swaps += 1
44+
end
45+
46+
cycle_start += 1
47+
end
48+
49+
return array, swaps
50+
51+
end
52+
53+
print(cycle_sort([120, 20, 12, 1, 5, 5, 78], [0]))

0 commit comments

Comments
 (0)