Binary Search

An efficient algorithm for solving the guessing game is known as binary search. It takes advantage of the fact that the numbers between 1 and 100 are in order from lowest to highest. Given that fact, by guessing the midpoint of the range each time, you can effectively eliminate half the numbers in the list on each guess -- hence the name binary search.

For example, suppose we do the guessing game on the numbers 1 to 16.

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16.

The optimal guess would be to guess the number at the midpoint of the range. Then after each guess you can effectively eliminate (approximately) half of the remaining numbers. For example, suppose the secret number is 13. Our first guess would be 8, which is too low. So we eliminate the bottom half of the range, leaving:

                       9, 10, 11, 12, 13, 14, 15, 16.
Our next guess would be 12, which is also too low, so we eliminate the bottom half of that range:
                                     13, 14, 15, 16.
Our next guess would be 14, which is too high, so we eliminate the top half of that range, giving:
                                     13

Our final guess is 13, which is the secret number. So, in this case it took us 4 guesses to find the secret number.

The Binary Search Algorithm

Here's a pseudocode version of the binary search algorithm for the guessing game.
Repeat until your guess is correct or until you run out of numbers in the list.
    Guess that the target number is the middle number in the list.
    If the guess is too high,
       Cut off the top half of the list.
    If the guess is too low,
       Cut off the bottom half of the list.
    If the guess is correct,
       Stop.
If you ran out of numbers, the target number is not in the list.

How does that compare to the pseudocode that your team came up with?

Some Observations About Binary Search