为什么我的bubort"如果"声明不起作用?

时间:2014-08-11 15:00:50

标签: ruby if-statement bubble-sort

我试图让冒泡排序方法起作用。问题发生在if语句中,我必须比较下一个索引的数字和数字。这是代码:

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)

这就是我得到的错误:

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>'

通过查看错误消息,我似乎得到了一个错误,因为我与nil相比,但我不明白为什么。

2 个答案:

答案 0 :(得分:1)

一种解决方案是使用枚举器来提高迭代效率。见Enumerator。这里我们使用Array#each_index从数组中提取枚举数。该解决方案基于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

输出:

[1, 2, 3, 4, 9]

答案 1 :(得分:0)

由于are[j+1]不存在,因此返回nil,无法与数字进行比较。

要解决此问题,请尝试稍微更改一下代码:

def bubble_sort(arr)
  arr.each do |i|
    arr.each_index do |j|
      begin
        puts "works" if arr[j] > arr[j+1] 
      rescue ArgumentError => e
        # HANDLE EXCEPTION HERE
      end
    end     
  end
end 

rescue将从该行的ArgumentError中抢救您的代码,从而在一定程度上修复您的代码。我不完全确定你想用这段代码实现什么,所以我不打算为你写。

但是,如果你想要一个现成的方法来排序,就像你似乎需要的那样,这是一个解决方案:

[1,3,2,5,4].sort         #=> [1,2,3,4,5]
# and for descending order, just do:
[1,3,2,5,4].sort.reverse #=> [5,4,3,2,1]
%w[little adam apple boy].sort #=> ["adam", "apple", "boy", "little"]