1

Ruby's Array#bsearch assumes a sorted array, takes a block returning true/false, and uses a binary search to find the first element for which the block returns true. For example:

ary = [0, 4, 7, 10, 12]
ary.bsearch {|x| x >=   4 } #=> 4

I want a version that also uses binary search, but returns the index of the found value, rather than the value itself. In the above example, it would return 1.

I was not able to find any such built in method -- is there one? If not, are there any other builtins I could use to achieve this? Alternatively, does ruby have any built in structures that support both search and insert in n log n time?

alk
  • 69,737
  • 10
  • 105
  • 255
Jonah
  • 15,806
  • 22
  • 87
  • 161

0 Answers0