Skip to content

Instantly share code, notes, and snippets.

@Nina07
Created October 20, 2021 06:58
Show Gist options
  • Save Nina07/412718a631ee700c8b3ce82c310f8f3d to your computer and use it in GitHub Desktop.
Save Nina07/412718a631ee700c8b3ce82c310f8f3d to your computer and use it in GitHub Desktop.
Given an array, sort it in a wave form such that; a1 <= a2 >= a3 <= a4 => a5 <= a6
class WaveSort
def initialize(ary)
@input_ary = ary
end
# OPTIMIZED, checking current value against the next/prev element
def wave_sort_optimized
ary_len = @input_ary.length
(0...@input_ary.length).step(2) do |i|
if (i > 0) && (@input_ary[i] > @input_ary[i-1])
swap(i, i-1)
end
if (i < ary_len-1) && (@input_ary[i] > @input_ary[i+1])
swap(i, i+1)
end
end
@input_ary
end
# BRUTE FORCE - sort then swap
def wave_sort
@input_ary.sort!
ary_len = @input_ary.length - 1
(1...ary_len).step(2) do |i|
swap(i, i+1, @input_ary)
end
@input_ary.compact
end
def swap(i, j, ary = @input_ary)
ary[i], ary[j] = ary[j], ary[i]
end
end
w = WaveSort.new([10,90,49,2,1,5,23])
e = WaveSort.new([1.25,2.0,2.2,4.20,3.15,5.00])
d = WaveSort.new([2,-1,4,3,-6,-3,5,4])
print "The array after performing a wave sort look like: \n"
print w.wave_sort_optimized
print "\n"
print e.wave_sort_optimized
print "\n"
print d.wave_sort_optimized
print "\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment