【问题标题】:Why is my bubblesort "if" statement not working?为什么我的冒泡排序“if”语句不起作用?
【发布时间】:2014-10-04 11:08:25
【问题描述】:

我正在尝试使用冒泡排序方法。问题出现在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 进行比较,但我不明白为什么。

【问题讨论】:

  • arr.each_index do |j| 到达最后一个索引时,arr[j+1] 将返回 nil,因为该索引不存在。
  • 哦,是的,但是我怎么能绕过这个呢?像 arr.each_index-1?
  • 八月是正确的。您可以通过使用 arr.each_with_index 来避免它,它返回特定元素的索引。当它在 arr.length -1 (最后一个元素)时,你停下来。但是使用冒泡排序,您不必在以后遍历数组时总是走到数组的末尾。

标签: ruby if-statement bubble-sort


【解决方案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]

【讨论】:

    【解决方案2】:

    因为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"]
    

    【讨论】:

    • 请不要在专业程序员的网站上教这些坏习惯。首先,捕获所有个异常,而不仅仅是特定的异常,其次,如果修复底层问题,则隐藏导致异常的错误。
    猜你喜欢
    • 2015-06-29
    • 2012-06-26
    • 2019-11-23
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多