Is there a built-in binary-search In Ruby?

后端 未结 3 1455
北恋
北恋 2020-12-05 23:05

I am looking for a built-in Ruby method that has the same functionality as index but uses a binary search algorithm, and thus requires a pre-sorted array.

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 23:41

    A lot has changed since 2011, in Ruby 2.3, you can use bsearch_index

    https://ruby-doc.org/core-2.3.0/Array.html#method-i-bsearch_index

    array.bsearch_index { |val| query <=> val }

提交回复
热议问题