## Algorithmathon Day 15: Binary Search

Created: 12 August 2013  Modified:

On day 15 we will be looking into the Binary Search. It is a relatively straight forward algorithm for searching ordered data. Its a simple process where you pick an arbitrary location to start. You compare the value you are searching for with the value from the location selected. If the search value is higher you pick a value to the right for the next search. The search value might be lower in which case you would pick a value to the left. The key is to track the highest and lowest known value locations and to pick the middle location between them. This would work something like the following.

1. The first value and the last value are the low and high locations.
2. Pick the value in the middle of the the high and low values. Call this current value.
3. If the high and low values are equal then return nothing.
4. If the high location is greater than the number of values return nothing
5. If the low location is less than the first value location return nothing
6. If the search value is less than the current value make the current value location the high location and go to step 2.
7. If the search value is greater than the current value make the current location the low location and go to step 2.
8. Return the value location

As always we begin with our RSpec tests.

algorithm_array_spec.rb

And the code to satisfy these tests.

algorithm_array_spec.rb

tags: Algorithm - Algorithmathon - Binary Search - RSpec - Ruby
Less Is More