Searching Algorithms

Lesson 5 of 20

Chase 49 through a sorted array as low, mid and high halve the window — then watch linear search crawl the long way.

The big picture

Two ways to hunt

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 elements one by one, in any order. 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. One comparison eliminates half the array.

Halving power

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

Java ships one

Arrays.binarySearch(a, 49) does it for you — it returns the index, or -(insertionPoint) - 1 when the value is missing.

Where you meet it

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