Search code examples
rubycomparisonargument-error

Comparison of Integer with nil failed in bubble sort algorithm


I am creating a bubble sort algorithm. Why do I get the error message comparison of Integer with nil failed (ArgumentError)?

def bubble_sort(arr)

  arr.each_with_index do |i, j|    
    print arr[j]
    print arr[j+1]

    if arr[j] > arr[j+1]
      print "swap"
    end 
  end

  print arr

end

bubble_sort([4,3,78,2,0,2])

Solution

  • First, you ask the script to read the J+1 index when the last index could be j. Or in other words you are asking to access a nil value in array. You have to ensure that you are not try to access n+1 element in your array. Simply just check and break from loop if you reach the last element:

    break if arr.size-1 == j #j is the last index now 
    

    Second, you are not doing anything in your code but printing. You can do something

    temp = arr[j]
    arr[j] = arr[j+1]
    arr[j+1] = temp