Searching Algorithms

Lesson 5 of 20

Hunt for 55 in a sorted array and watch binary search shrink the window in half at every comparison.

The big picture

Why search fast

Finding one value inside a million is the most common job in computing — the trick is to stop looking at values you can already rule out.

Two contestants

Linear search checks every element one by one. Binary search only works on sorted data — but it is dramatically faster.

The sorted shortcut

If a[mid] is smaller than the target, everything left of mid is smaller too. Half the array is eliminated in one look.

Halving power

1,024 elements take at most 10 comparisons; 1,000,000 elements take about 20. Each comparison halves the window.

Where you meet it

Dictionary pages, git bisect, database indexes and autocomplete all ride on binary search or its cousins.