This is a binary search implementation that returns the last element found.
The behavior is very similar to that of the existing
Array#bsearch and Array#bsearch_index methods,
except Find-minimum mode is replaced by a Find-maximum mode.
In Find-maximum mode, the last element/index for which the block
evaluates to true is returned, as opposed to the first.
Analogously to the conditions in the block for the normal bsearch and
bsearch_index methods, in bsearch_last and bsearch_last_index the block
needs to satisfy the following in the Find-maximum mode:
The block is such that all true-evaluating elements precede all
false-evaluating elements. This is the exact opposite of the condition for
bsearch.
Examples:
a = [0, 4, 7, 10, 12]
a.bsearch_last {|x| x<=4 } # => 4
a.bsearch_last {|x| x<=6 } # => 4
a.bsearch_last {|x| x<=-1 } # => nil
a.bsearch_last {|x| x>=100 } # => nilThe Find-any mode behaves the same as in the Array#bsearch methods.
Run rake build. This takes the steps:
- create Makefile with
ruby extconf.rb - create .so file with
make - the .so file can be imported into Ruby with
require bsearch_last.so(normally the extension is not needed, Ruby checks these files automatically, but here there's another file with the same name and therbextension, which takes precedence).
require 'bsearch_last'
[1, 1, 2, 2, 3, 4].bsearch_last_index {|x| x <= 2 } # => 3Run rake. This tests the Ruby and C versions of the functions.
rake bench
The C version is about 30% faster than the Ruby one for the somewhat long array used in the benchmark.