Class: Algorithmable::Search::Binary

Inherits:
Object
  • Object
show all
Defined in:
lib/algorithmable/search/binary.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.lookup(element, in_collection) ⇒ Object



4
5
6
# File 'lib/algorithmable/search/binary.rb', line 4

def self.lookup(element, in_collection)
  new.lookup(element, in_collection)
end

Instance Method Details

#lookup(element, collection) ⇒ Object



8
9
10
# File 'lib/algorithmable/search/binary.rb', line 8

def lookup(element, collection)
  traverse element, collection, 0, collection.length - 1
end

#traverse(element, collection, low, high) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/algorithmable/search/binary.rb', line 12

def traverse(element, collection, low, high)
  while low <= high
    mid = low + (high - low) / 2
    if element < collection[mid]
      high = mid.pred
    elsif element > collection[mid]
      low = mid.next
    else
      return mid
    end
  end
end