Searching Smart
Can you guess a number from 1 to 100 in seven tries? Compare slow one-by-one searching with the fast trick of cutting the list in half.
Welcome back!
Step 1 of 12Learn
The guessing game
Your friend thinks of a number from 1 to 100. After each guess, they say "higher" or "lower."
One way: guess 1, then 2, then 3... If the number is 99, that takes 99 guesses! Checking items one by one from the start is called linear search.
A smarter way: guess 50, the middle. If they say "higher," you know it is 51 to 100. You just threw away half the numbers with one guess! Then guess the middle of what is left, 75, and keep going.
Step 2 of 12Practice · Choose one
The secret number is between 1 and 100. What is the best first guess?
Step 3 of 12Learn
Binary search
Always guessing the middle and throwing away half is called binary search. Binary means "two," because each guess splits the list into two parts.
Watch how fast the numbers shrink: 100, then 50, 25, 13, 7, 4, 2, 1. That is only 7 guesses to find any number from 1 to 100!
There is one rule: binary search only works on a sorted list. The numbers or words must be in order, like a dictionary.
Step 4 of 12Practice · Put in order
The secret number is 70. Put these binary search guesses in the order they happen.
Drag the items, or use the arrow buttons, to put them in order.
- Guess 71: "lower"
- Guess 62: "higher"
- Guess 75: "lower"
- Guess 70: "got it!"
- Guess 68: "higher"
- Guess 50: "higher"
Step 5 of 12Diagram
Halving 100 numbers
Each middle guess throws away half of what is left.
- Start
100 numbers left
- After guess 1
50 numbers left
- After guess 2
25 numbers left
- After guess 3
13 numbers left
- After guess 4
7 numbers left
- After guess 5
4 numbers left
Step 6 of 12Try the calculator
How many guesses?
Type how many numbers are in the game. See the worst case for one-by-one guessing and for halving.
- One by one (worst case)
- 100
- Binary search (worst case)
- 7
Step 7 of 12Practice · Estimate
Guess: with binary search, how many guesses do you need at most to find one number out of 1,000?
Step 8 of 12Chart
Worst-case guesses as the list grows
| Numbers in the list | One by one | Binary search |
|---|---|---|
| 10 | 10 | 4 |
| 100 | 100 | 7 |
| 1,000 | 1,000 | 10 |
Step 9 of 12Practice · True or false
Binary search works on any list, even if it is all mixed up.
Step 10 of 12Note
Step 11 of 12Compare
Linear search vs. binary search
| Aspect | Linear search | Binary search |
|---|---|---|
| How it works | Check items one by one from the start | Check the middle, throw away half |
| List must be sorted? | No | Yes |
| Worst case for 100 items | 100 checks | 7 checks |
| Good for | Short or mixed-up lists | Long sorted lists |
Step 12 of 12Practice · What would you do?
What would you do?
Your class has a messy pile of 30 library books in no order. You want to find the one about sharks. Which search should you use?
Lesson complete!