1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Items Left16
Steps Taken0

The Needle in the Haystack

Imagine you have 16 boxes sorted in order. You want to find box #13. A 'Linear' robot would check 1, then 2, then 3... all the way to 13. That's slow!

Cut in Half

The 'Logarithmic' robot cuts the line perfectly in the middle. It picks box #8. 'Is the secret number (13) bigger or smaller than 8?'

Throw Away Half

13 is BIGGER than 8! So we know the answer cannot be on the left. We throw away boxes 1-8 instantly. POOF! Half the problem is gone.

Cut Again

Now we have 8 boxes left. We cut in the middle again (box #12). 'Is 13 bigger or smaller than 12?'

Throw Away Again

13 is BIGGER than 12! So we throw away the left side again. The problem is getting tiny!

Almost There

Only 4 boxes left. We check the middle (box #14). 'Is 13 bigger or smaller than 14?'

Too Big!

13 is SMALLER than 14! So this time, we throw away the right side.

Found It!

Only one box left: #13. We found it in just 3-4 jumps! A Linear robot would have taken 13 steps. This is the power of O(log n).

Mastered.

You now understand the secret shortcut of algorithms.

AlgoAnimator: Interactive Data Structures