Add Binary Search To Arrays In Ruby
Join the DZone community and get the full member experience.Join For Free
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
(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 => nilNote: 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.
Opinions expressed by DZone contributors are their own.