From 0ff7252ef90afb0e066a1926949017eb902719c2 Mon Sep 17 00:00:00 2001 From: Harsh Kumar <61012869+cyrixninja@users.noreply.github.com> Date: Mon, 2 Oct 2023 12:15:43 +0530 Subject: [PATCH] Added Odd Even Sort Algorithm --- sorting/odd_even_sort.rb | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 sorting/odd_even_sort.rb diff --git a/sorting/odd_even_sort.rb b/sorting/odd_even_sort.rb new file mode 100644 index 0000000..7e038c7 --- /dev/null +++ b/sorting/odd_even_sort.rb @@ -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