Search code examples
rubybubble-sort

Where is the bug in my bubble sort code?


I see that there are better ruby bubble sort codes already posted in places such as here: Using the Bubble sort method for an array in Ruby But I am having trouble debugging my current code and would appreciate some help with figuring out why my code does not work. Thanks.

def bubble_sort(arr)
    original = arr
    x = 0
    while x < arr.count - 1
        if arr[x] < arr[x + 1]
            y = arr[x + 1]
            arr[x + 1] = arr[x]
            arr[x] = y
        end
        x += 1
    end
    if original == arr
        return arr
    else
        return bubble_sort(arr)
    end 
end

Solution

  • Four issues :

    1. bubble_sort[arr] does not work - you should call bubble_sort(arr)
    2. original == arr - will always be true, since you assigned it to arr before - you should have assigned it using dup - original = arr.dup
    3. arr[x] < arr [x+1] will create an array sorted in reverse order...
    4. you should change the local copy rather than the one you got as parameters - result = arr.dup rather than original = arr.dup

    The code after the above fixes:

    def bubble_sort(arr)
      result = arr.dup
      x = 0
      while x < result.count - 1
        if result[x] > result[x + 1]
          y = result[x + 1]
          result[x + 1] = result[x]
          result[x] = y
        end
        x += 1
      end
      if arr == result
        return result
      else
        return bubble_sort(result)
      end 
    end
    
    bubble_sort([1,3,5,2,4])
    # => [1, 2, 3, 4, 5]