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

烈酒焚心 提交于 2019-11-27 21:51:25
Marc-André Lafortune

Ruby 2.0 introduced Array#bsearch and Range#bsearch.

For Ruby 1.9, you should look into the bsearch and binary_search gems. Other possibility is to use a different collection than an array, like using rbtree

bsearch is in my backports gem, but this is a pure Ruby version, so quite a bit slower. Note that a pure Ruby binary search will still be faster than a linear builtin search like index or include? for big enough arrays/ranges (or expensive comparisons), since it's not the same order of complexity O(log n) vs O(n).

To play with it today, you can require 'backports/2.0.0/array/bsearch' or require 'backports/2.0.0/range/bsearch'.

Good luck!

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 }

I use bsearch. This is how it works:

array = ['one', 'two', 'three', 'four', 'five']

search = array.sort.bsearch { |value| 'four' <=> value }

Note: binary search needs a sorted array; this adds a li'l overhead but it's fine, compared to the speed of the search.

search will return the value four of the array, else nil if it doesn't find the value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!