Ruby二进制搜索 - Ruby binary search

- 此内容更新于:2016-02-02
主题:

我想做一个二进制搜索100万雇员id的列表,已经解决。我得到错误:还有,我想这样的,如果是在列表中,它将返回。

原文:

I'm trying to do a binary search on a list of 1 million employee IDs, already sorted out.

def exist?(id)
  lower = -1
  upper = $employee_list.count
  while true
    mid = (lower + upper) / 2
    if upper == lower + 1
      return nil
      if id == $employee_list[mid]
        return mid
        if id < $employee_list[mid]
          upper = mid
        else
          lower = mid
        end
      end
    end
  end
end

I get the error:

NoMethodError:undefined method 'call' for nil:NilClass

Also, I'm trying to make it such that if exist?(54) is in the list, it will return true.

网友:这里没有。

(原文:There's no call here.)

网友:我也能理解,作为一个练习,您可能想要编写代码来做一个二进制搜索,但提到“100万雇员id”认为这是一个任务一个实际的应用程序。如果是这样,你为什么要重复工作,而不是使用数据库或搜索使用Ruby的内置数组#bsearch方法?介绍了该方法在v2.0中,但我相信一定有很多宝石,为早期版本提供了相同的功能。

(原文:I can understand why, as an exercise, you might want to write code to do a binary search, but the mention of "1 million employee IDs" suggests it's a task for an actual app. If so, why would you reinvent the wheel, rather than just searching with a database or using Ruby's built-in Array#bsearch method? That method was introduced in v2.0, but I'm sure there must be many gems that provide the same functionality for earlier versions.)

网友:“越来越错误”带给我的脸,微笑,因为它是我们都经历过:当看似正确的代码不工作,我们只是运行一遍,保持不变,奇怪的是得到同样的错误的答案或错误消息。

(原文:"keep getting the error" brings a smile to my face, as it's something we've all experienced: when seemingly correct code doesn't work, we just run it again, unchanged, and strangely get the same wrong answer or error message.)

解决方案:
只使用:至于错误——它来自其他地方。
原文:

Just use Array#bsearch:

$employee_list.bsearch { |employee| id <=> employee }

As for the error - it comes from somewhere else.