Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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
  
   

usage:


   
(0..100).to_a.bsearch(12)
=> 12
(0..100).to_a.bsearch(-1)
=> 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 
   ruby-bsearch.
  
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}