Back

Activity 2.10: Binary Search

divider

Activity 2.10

Binary Search

Key Concepts

Halving the Problem

Tracking low, mid, and high

The Sorted Requirement

Failing Quietly

Activity 2.9 Opened Every Door

Linear search's worst case checks every element: eight doors in the haunted house, a million names in a list of a million.

There is a way to search a million names in twenty checks, and you already use it whenever you look something up in a dictionary. It costs one thing linear search never needed.

Nobody Reads a Dictionary From Page One

Looking for otter, you open near the middle. You land on marble: otter comes after it, so the whole first half of the book is gone in one look.

Open the middle of what is left, and do it again. Every look throws away half of the pages that remain — and it only works because a dictionary is in alphabetical order.

Every Check Throws Away Half

A 1000-page dictionary. Predict how many looks it takes to get down to a single page.

Every Check Throws Away Half

Value Trace
Pages left to search: 1000
after 1 check: 500
after 2 checks: 250
after 3 checks: 125
after 4 checks: 62
after 5 checks: 31
after 6 checks: 15
after 7 checks: 7
after 8 checks: 3
after 9 checks: 1

Nine looks narrow a thousand pages to one, and a tenth reads it: ten looks at most, against up to a thousand page by page. Double the book to 2000 pages and it takes one more look. That is why it scales.

low and high Are the Edges of What Is Left

In code, the dictionary is a sorted array. Two variables mark the part still worth searching: low starts at the first index and high at the last.

Demo
int[] ids = { 104, 211, 358, 407, 512, 663, 729, 810 };

low and high Are the Edges of What Is Left

Each pass looks at the middle index, mid, between the two edges. The loop keeps going while there is anything left between them.

Demo
int low = 0;
int high = ids.Length - 1;
while (low <= high)
{
int mid = (low + high) / 2;
// check ids[mid], then move one edge
}
return -1;

low and high Are the Edges of What Is Left

Too small? The target is to the right: move low past the middle. Too big? It is to the left: move high.

Demo
if (ids[mid] == target)
{
return mid;
}
else if (ids[mid] < target)
{
low = mid + 1;
}
else
{
high = mid - 1;
}

Activity 1.6's Trap Is Exactly Right Here

(low + high) / 2 divides two ints, so C# throws the remainder away: (0 + 7) / 2 is 3, not 3.5.

In Activity 1.6 that silent rounding was a bug waiting to happen. Here it is the whole point: an index has to be a whole number, and there is no element at position 3.5. The exam notation has to do extra work for this, as the panel further down shows.

Three Searches, Three Answers

Put the two pieces together into a method, Find(int target), that searches ids. Predict all three outputs. 500 is not in the array.

Demo
Console.WriteLine(Find(407));
Console.WriteLine(Find(104));
Console.WriteLine(Find(500));
Demo
3
0
-1

Three Searches, Three Answers

Follow the search for 500, one check per row.

Value Trace
Find(500) ids = { 104, 211, 358, 407, 512, 663, 729, 810 }
check low high mid ids[mid]
1 0 7 3 407 too small: low = 4
2 4 7 5 663 too big: high = 4
3 4 4 4 512 too big: high = 3
4 3 low > high: return -1

The edges cross after three checks, and nothing is left to look at. Linear search would have needed all eight.

Binary Search Needs a Sorted Array

Every step trusts that “too small” means the target is to the right. That is only true if the array is sorted.

Here 211 and 729 have swapped places. 211 is still in the array. Predict what Find(211) returns.

Demo
int[] ids = { 104, 729, 358, 407, 512, 663, 211, 810 };
Console.WriteLine(Find(211));
Demo
-1

Binary Search Needs a Sorted Array

-1: not found. The first check lands on 407, which is bigger than 211, so the search throws away everything to the right — including position 6, where 211 now sits.

No error, no warning, no crash. Just a confident wrong answer. Those are worse than crashes, because a crash at least tells you something went wrong.

There Is No Winner, Only a Fit

Unsorted, or searched only once: linear search. Sorting takes work, and one search does not repay it.

Sorted, and searched often: binary search. The cost of sorting is paid once and every search after that is fast.

Activity 2.12 asks how much sorting costs, which is the other half of this decision.

Today's Objectives

  • Explaining binary search as repeated halving
  • Tracking low, mid, and high through a search
  • Finding the worst case and seeing how slowly it grows
  • Showing that binary search on bad information fails without an error

Key Terms

Binary search
Repeatedly checking the middle of a sorted list and throwing away the half that cannot hold the target.
Midpoint
The index halfway between the current low and high.
Silent failure
A wrong answer produced with no error message.

'F' → Fullscreen

divider

Same Idea, Exam Notation

The opening of the deck's Find, written the way the AP exam would write it.

C#
int low = 0;
int high = ids.Length - 1;
while (low <= high)
{
int mid = (low + high) / 2;
// ...
}
Exam Notation
low ← 1
high ← LENGTH(aList)
REPEAT UNTIL(low > high)
{
sum ← low + high
mid ← (sum - (sum MOD 2)) / 2
// ...
}

1. The Edges Start at 1 and LENGTH

Exam lists start at index 1, so low starts at 1 and high at LENGTH(aList). The same search on the same list gives an answer one higher than C# does, as in Activity 2.9.

2. The Sheet's / Does Not Round

On the reference sheet, / is ordinary division: 9 / 2 is 4.5. C# gets the whole-number midpoint for free, from integer division; the exam has to build it.

It uses Activity 1.6's other tool: take away the remainder, then divide. When sum is 9, 9 MOD 2 is 1, and (9 - 1) / 2 is 4. When sum is 12, 12 MOD 2 is 0, and 12 / 2 is already 6.

Worth noticing: the reference sheet is small on purpose, so some familiar operations have to be rebuilt from the pieces it does have.

divider

Build: Raylib Lab 9

Today's build is Raylib Lab 9, straight after this deck. You draw an array as a row of bars and step linear search and binary search through it one key press at a time, so you can watch binary search throw half the array away with every check.

Go to Activity 2.11: Raylib Lab 9 — Visualizing a Search

Raylib programs run on the classroom computers, so this one is built in class. Everything you hand in today is listed on the lab's page.

divider

On to the Lab