Over a million developers have joined DZone.

Add Binary Search To Arrays In Ruby

DZone's Guide to

Add Binary Search To Arrays In Ruby

Free Resource
A tiny snippet adding binary search to [sorted] Arrays. It returns the array index if found and nil otherwise.

class Array
  def bsearch(e, l = 0, u = length - 1)
    return if l>u;m=(l+u)/2;e


=> 12
=> nil
(0..100).to_a.bsearch(12, 50, 100) # defining upper and lower bound indices
=> nil

Note: this does 
   not guarantee to find the lowest index occurrence of an element, only the one it hits first. If you require that safety, try 

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}