Binary Search

Binary Search is a way to efficiently search an array of items by halving the search space each time.

An example that demonstrates Binary Search:

Write a function that returns either the location of the target value in the array, or -1 if the array does not contain the target value.

Pseudocode: 
  1. Let min = 0 and max = n
  2. If max < min, then stop: target is not present in the array. Return -1.
  3. Guess the average of max and min, rounded down so that it is an integer
  4. If you guessed the number, stop.  You found it!
  5. If the guess was too low, set min to the one larger than the guess.
  6. If the guess was too high, set max to the one smaller than the guess.
  7. Go back to step 2. (while loop — don’t use “for” loop because the binary search doesn’t guess the indices by sequential order. )

My solution in Ruby: 

screen-shot-2016-11-09-at-3-11-42-pm

Running the code yields the expected outputs:

screen-shot-2016-11-09-at-3-24-13-pm

Advertisements
Binary Search

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s