Search⌘ K
AI Features

A Guessing Game

Discover how different search algorithms work by playing a guessing game. Learn the concepts of linear search and binary search, and understand how binary search reduces the number of guesses needed by eliminating half the possibilities each time. This lesson helps you grasp the efficiency differences between search methods and prepares you to apply these algorithms in computer science.

We'll cover the following...

Let's play a little game to give you an idea of how different algorithms for the same problem can have wildly different efficiencies. The computer is going to randomly select an integer from 1 to 16. You have to guess the number by making guesses until you find the number that the computer chose. Let's begin.

Maybe you guessed 11, then 22, then 33, then 44, and so on, until you guessed the right number. We call this approach linear search, because you guess all the numbers as if they were lined up in a row. It would work. But what is the highest number of guesses you could need? If the computer selects 1616, you would need 1616 guesses. Then again, you could be really lucky, which would be when the computer selects 11 and you get the number on your first guess. How about on average? If the computer is equally likely to select any number from 1 to 16, then on average you'll need 8 guesses.

But you could do something more efficient than just guessing 1,2,3,4,1, 2, 3, 4, …, right? Let's consider another example where the computer is going to randomly select an integer from 11 to 3030. Since the computer tells you whether a guess is too low, too high, or correct, you can start off by guessing 1515. If the number that the computer selected is less than 1515, then because you know that 1515 is too high, you can eliminate all the numbers from 1515 to 3030 from further consideration. If the number selected by the computer is greater than 1515, then you can eliminate 11 through 1515. Either way, you can eliminate about half the numbers. On your next guess, eliminate half of the remaining numbers. Keep going, always eliminating half of the remaining numbers. We call this halving approach binary search, and no matter which number from 11 to 3030 the computer has selected, you should be able to find the number in at most 55 guesses with this technique.

Here, try it for a number from 11 to 300300. You should need no more than 99 guesses.

How many guesses did it take you to find the number this time? Why should you never need more than 99 guesses? (Can you think of a mathematical explanation)?

We'll return to binary search, and we'll see how you can use it to efficiently search for an item in an array. But first, let's look at an algorithm for a trickier problem.