Search code examples
arraysrubybubble-sort

Running Through a Ruby Bubble Sort


I'm writing a bubble sort code as part of a beginner's class on Ruby. I know that (array.length - 1).times do |i| is bad practice because I don't need to run to the end of an array each time. (In my example, [5,4,3,2,1] five is moved to the end during the first run through, the four is in its right place by the end of the second, etc., so there's no need to examine those numbers again):

def bubble_sort(array)
  (array.length - 1).times do
    (array.length - 1).times do |i|
      array[i], array[i+1] = array[i+1], array[i] if array[i] > array[i+1]
    end 
  end
end

bubble_sort([5,4,3,2,1])

Is there a neat way to tell the method to examine one fewer element of the array each time?


Solution

  • What about adding a variable j in the outer loop and substracting j from array.length - 1 ?

    It would look like that:

    def bubble_sort(array)
      (array.length - 1).times do |j|
        (array.length - 1 - j).times do |i|
          array[i], array[i+1] = array[i+1], array[i] if array[i] > array[i+1]
        end 
      end
    end
    
    bubble_sort([5,4,3,2,1])