user3385759 user3385759 - 5 months ago 11
Ruby Question

Compare two consecutive elements in an array

I want to create a "bubble sort" method, which means that I take two consecutive elements in an array, compare them and if the left element is greater than the right element, they should switch the position. I want to repeat it until my array is sorted in ascending order.

My code only works partially. If my array is too big nothing will happen (I have to quit ruby with CTRL + C). With arrays smaller than 5 elements my code works fine:

def bubbles(array)

while array.each_cons(2).any? { |a, b| (a <=> b) >= 0 }

# "true" if there are two consecutives elements where the first one
# is greater than the second one. I know the error must be here somehow. do | number, index |
if array[index + 1].nil?
elsif number > array[index + 1]
array[index], array[index + 1] = array[index + 1], array[index] # Swap position!

p array

If I call my method with an array with 4 elements, it works fine:

bubbles([1, 5, 8, 3]) # => [1, 3, 5, 8]

If I call it with a bigger array, it doesn't work:

bubbles([5, 12, 2, 512, 999, 1, 2, 323, 2, 12]) # => Nothing happens. I have to quit ruby with ctrl + c.

Have I somehow created an infinite loop with my while statement?


The problem is in your stop condition. You won't stop until you have an array where each element is lesser than the next. But in your long array you have duplicated elements, so the sorted elements will have adjacent elements that are equal to each other.

Not being too fancy with your code will make your life easier :)

while array.each_cons(2).any? { |a, b| a > b }