为什么我的bsearch版本不起作用?

时间:2015-04-26 02:59:54

标签: ruby recursion binary-search

我正在运行bsearch([1,2,3,4,5,6], 6)

这是我的bsearch版本:

def bsearch(arr, target)

    return nil if arr.size == 0

    half = arr.size / 2
    left = arr[0...half]
    right = arr[half...-1]

    case target <=> arr[half]
    when 1
      return half + bsearch(right, target)
    when 0
      return half
    when -1
      return bsearch(left, target)
    end
end

这是我被抛出的错误:

recursion.rb:224:in `+': nil can't be coerced into Fixnum (TypeError)
    from recursion.rb:224:in `bsearch'
    from recursion.rb:224:in `bsearch'
    from recursion.rb:249:in `<main>'

2 个答案:

答案 0 :(得分:1)

来自ruby docs

  

..包括从开始到结束。那些创建使用   ...排除最终值

您的代码不包括最终的数组元素。

left = arr[0...half]
right = arr[half...-1]

使用..而不是...

更改为使用范围运算符
left = arr[0..half]
right = arr[half..-1]

答案 1 :(得分:0)

您应该添加一些调试代码,它可以帮助您节省大量时间并找到根本原因。

def bsearch(arr, target)

    return nil if arr.size == 0

    half = arr.size / 2
    puts "half: #{half}"
    left = arr[0...half]
    puts "left:#{left}"
    puts "arr:#{arr}"
    right = arr[half...-1]
    puts "right:#{right}"
    ....
end

结果:

left:[1, 2, 3]
arr:[1, 2, 3, 4, 5, 6]
half:3
right:[4, 5]
left:[4]
arr:[4, 5]
half:1
right:[]
test.rb:16:in `+': nil can't be coerced into Fixnum (TypeError)
    from test.rb:16:in `bsearch'
    from test.rb:16:in `bsearch'
    from test.rb:24:in `<main>'

然后你会发现一些问题。

  1. 右:[4,5] =&gt;它应该是[4,5,6]

  2. arr = [4,5]; half = 1; =&GT; right = arr [1 ...- 1] = []

    所以bsearch(right, target)将返回nil

  3. 您的代码应为:

    left = arr[0..half]
    right = arr[half..-1]