ViewWiki

Lesson 3 of 4

Searching and halving.

About 20 minutes · 5 practice questions

Two ways to find a name in a list: check them one by one, or open the middle and throw half away. Why binary search needs a sorted list, and how the base-two logarithm counts the halvings it needs.

Step 1 of 5 · Linear search

Step 3 of 5

How many halvings

How many halvings shrink a list of 1024 names to one? The same question backwards: how many doublings take one name to 1024? On the board, Growth per step is fixed at 2: each step doubles the stack, and Steps sets how many times.

The number of doublings of 2 that reach nn⁠ is the base-two logarithm, log⁡2n\log_2 n⁠. Binary search in nn⁠ sorted names needs about log⁡2n\log_2 n⁠ checks.

To the question

Step 4 of 5

A list twice as long

A linear search through a list twice as long does twice the work. What about binary search? On the board, the stack after ten steps already reaches 1024.

To the question

Step 5 of 5

A million

Look inside is open at Log scale: each doubling raises the stack by the same height, so exponential growth is a straight line. The logarithm turns multiplying into adding, which is why even huge lists need few halvings. A board of twelve steps only reaches 4096; work out the million yourself.

To the question

Interactive scene

Loading the interactive version…

Each step sets up the Scene for you, and a control marked “fixed” stays put for that step.

To the experiment

Practice · Reach the target

On the board each step doubles the stack; binary search goes the same way backwards, and halves. Change Steps until the last column reaches 1024, and press Check. That is the number of halvings that shrink 1024 names to one.

To the experiment

Practice · Predict, then look

In 1024 sorted names binary search needs ten checks. How many will it need in 2048 names, twice as many?

To the experiment

Practice · Calculate

A sorted phone book of a million names. At most how many checks does binary search need? (Hint: 210=10242^{10} = 1024⁠, nearly a thousand.)