Searching Algorithms

Lesson 5 of 20

Hunt for 60 in a sorted list as low, mid and high corner it in four probes — then watch linear search crawl.

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 needs sorted data — but pays off massively.

The sorted shortcut

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

Halving power

1,024 elements take at most 10 comparisons; 1,000,000 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.

Python extras

x in lst is a linear scan. The bisect module gives you a tuned, C-implemented binary search for sorted lists.