Ruby/Bsearch: a binary search library for Ruby

Ruby/Bsearch is a binary search library for Ruby. It can search the FIRST or LAST occurrence in an array with a condition given by a block.

Tha latest version of Ruby/Bsearch is available at <URL:http://namazu.org/~satoru/ruby-bsearch/> .

API

Array#bsearch_first (range = Range.new(0, self.length() - 1)) {|x| ...}

Return the index of the FIRST occurrence in an array with a condition given by block. Return nil if not found. Optional parameter `range' specifies the range of searching.

Array#bsearch_last (range = Range.new(0, self.length() - 1)) {|x| ...}

Return the index of the LAST occurrence in an array with a condition given by block. Return nil if not fount. Optional parameter `range' specifies the range of searching.

Array#bsearch_range (range = Range.new(0, self.length() - 1)) {|x| ...}

Return both the FIRST and the LAST occurrence in an array with a condition given by block as Range object. Return nil if not found. Optional parameter `range' specifies the range of searching.

Array#bsearch (range = Range.new(0, self.length() - 1)) {|x| ...}

This is an alias to Array#bsearch_first.

Example

% irb --simple-prompt -r 'bsearch.rb'
>> %w(a b c c c d).bsearch_first {|x| x <=> "c"}
=> 2
>> %w(a b c c c d).bsearch {|x| x <=> "c"} # same as above
=> 2
>> %w(a b c c c d).bsearch_last {|x| x <=> "c"}
=> 4
>> %w(a b c c c d).bsearch {|x| x <=> "x"}
=> nil
>> %w(a b c c c d).bsearch_range {|x| x <=> "c"}
=> 2..4

Download

Ruby/Bsearch is a free software with ABSOLUTELY NO WARRANTY under the terms of Ruby's licence.

satoru@namazu.org