mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-27 21:58:57 +01:00
Added Odd Even Sort Algorithm
This commit is contained in:
parent
2f6c267980
commit
0ff7252ef9
1 changed files with 29 additions and 0 deletions
29
sorting/odd_even_sort.rb
Normal file
29
sorting/odd_even_sort.rb
Normal file
|
@ -0,0 +1,29 @@
|
||||||
|
#Odd Even Sort
|
||||||
|
#https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort
|
||||||
|
|
||||||
|
def odd_even_sort(arr)
|
||||||
|
n = arr.length
|
||||||
|
sorted = false
|
||||||
|
|
||||||
|
while !sorted
|
||||||
|
sorted = true
|
||||||
|
(1..n - 2).step(2) do |i|
|
||||||
|
if arr[i] > arr[i + 1]
|
||||||
|
arr[i], arr[i + 1] = arr[i + 1], arr[i]
|
||||||
|
sorted = false
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
(0..n - 2).step(2) do |i|
|
||||||
|
if arr[i] > arr[i + 1]
|
||||||
|
arr[i], arr[i + 1] = arr[i + 1], arr[i]
|
||||||
|
sorted = false
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# Test
|
||||||
|
arr = [5, 10, 2, 9, 1, 5, 2, 6, 7, 8]
|
||||||
|
odd_even_sort(arr)
|
||||||
|
puts arr
|
Loading…
Reference in a new issue