Binary Search & Library Search
In short: scanning a list front to back (linear search) checks every
item and costs O(n) — it works on anything, sorted or not. Binary search
needs the data sorted, but then it opens the middle, decides which half the
answer must be in from one comparison, and throws the other half away: O(log
n). The whole thing rests on one invariant you must keep true every step — if
the target is anywhere, it's between lo and hi.

Find a title in a 50,000-track library
Each look halves what's left, so the number of looks is about log₂ n — double the library and you pay one more look, not thousands more:
n, looks = 1_000_000, 0
while n > 0:
n //= 2
looks += 1
print(looks)Invariant: if
titleis anywhere in the list, it is at an index inlo..hi(both ends included). Startlo = 0, hi = len - 1; a mismatch to the left ofmidsetslo = mid + 1, a mismatch to the right setshi = mid - 1; whenlo > hithe range is empty and the title isn't there.
Watch lo and hi close in on "Dawn" step by step. Now the same invariant
on a bigger shelf, with every look drawn:
Searching for "Glow": every look throws away half of what's left, so eight titles need only three looks.
The whole list is in play, so if "Glow" is anywhere it is between lo and hi. 8 cells. lo at index 0. hi at index 7.
The mistake people really make: getting the loop condition and the move off by one. This version looks right, and fails on the very last title:
This should print 2, the index of "Cove". It prints -1 — the search gives up while one title is still unchecked.