class Algorithmable::Searches::BinarySearch

Public Class Methods

lookup(element, in_collection) click to toggle source
# File lib/algorithmable/search/binary_search.rb, line 4
def self.lookup(element, in_collection)
  new.lookup(element, in_collection)
end

Public Instance Methods

lookup(element, collection) click to toggle source
# File lib/algorithmable/search/binary_search.rb, line 8
def lookup(element, collection)
  return if element.nil?
  traverse element, collection, 0, collection.length - 1
end
traverse(element, collection, low, high) click to toggle source
# File lib/algorithmable/search/binary_search.rb, line 13
def traverse(element, collection, low, high)
  while low <= high
    mid = low + (high - low) / 2
    value_at = collection[mid]
    if element < value_at
      high = mid.pred
    elsif element > value_at
      low = mid.next
    else
      return mid
    end
  end
end