I'm trying to get a bubble-sort method working. The problem occurs in the if
statement where I have to compare a number and the number on the next index. Here's the code:
numbers = [4, 2, 3, 1, 9]
def bubble_sort(arr)
arr.each do |i|
arr.each_index do |j|
if arr[j] > arr[j+1]
puts "works"
end
end
end
end #end method
bubble_sort(numbers)
And this is the error I'm getting:
sorting.rb:11:in `>': comparison of Fixnum with nil failed (ArgumentError)
from sorting.rb:11:in `block (2 levels) in bubble_sort'
from sorting.rb:9:in `each'
from sorting.rb:9:in `block in bubble_sort'
from sorting.rb:7:in `each_index'
from sorting.rb:7:in `bubble_sort'
from sorting.rb:19:in `<main>'
By looking at the error message it seems I get an error because I compare to nil, but I don't see why.
One solution is to use an enumerator to make iteration efficient. See Enumerator. Here we use Array#each_index
to extract an enumerator from the array. The solution is based from the Bubble sort described in Wikipedia.
#!/usr/bin/env ruby
numbers = [4, 2, 3, 1, 9]
def bubble_sort(arr)
return unless arr.size > 1
indices = arr.each_index
begin
swapped = false
i = indices.next
indices.each do |j|
a = arr[i]
b = arr[j]
if a > b
arr[i] = b
arr[j] = a
swapped = true
end
i = j
end
indices.rewind
end while swapped
end
bubble_sort(numbers)
puts numbers.inspect
Output:
[1, 2, 3, 4, 9]