Skip to content

Instantly share code, notes, and snippets.

@cpjk
Created March 13, 2016 06:12
Show Gist options
  • Save cpjk/4f4be14ca603fa0d0b03 to your computer and use it in GitHub Desktop.
Save cpjk/4f4be14ca603fa0d0b03 to your computer and use it in GitHub Desktop.
def wiggle_sort(ary)
return ary if ary.length < 2
ary = ary.sort
lo_index = 0
hi_index = ary.length.even? ? (ary.length / 2) : (ary.length / 2) + 1
new_ary = []
while true
new_ary << ary[lo_index] # add the number on the smaller side of the array
lo_index += 1
break if hi_index > ary.length - 1
new_ary << ary[hi_index] # add the number on the smaller side of the array
hi_index += 1
end
new_ary
end
p wiggle_sort([1, 5, 1, 1, 6, 4])
p wiggle_sort([1, 3, 2, 2, 3, 1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment