Binary search keeps an interval [lo, hi] that is guaranteed to contain the target if it exists, probes the middle, and discards the half that cannot contain it. One comparison therefore eliminates half the search space instead of a single element.
The invariant
- If the target exists, it lies inside [lo,hi].
- Every step either finds the target or shrinks the interval while preserving the invariant.
The probe
- mid=⌊(lo+hi)/2⌋ splits the interval into two halves.
- One comparison decides which half can still contain the target — half the candidates are eliminated.
Why O(log n)
- After k probes the interval length is at most n/2k.
- The search ends when the interval is empty, so k≤⌊log2n⌋+1.
- For n=1,000,000 that is at most 20 probes.
Sortedness is required
- The discard argument relies on every value left of mid being ≤a[mid] and every value right of it being ≥a[mid].
- Without sorted input, discarding a half is unsound.
Failure case
- When lo>hi the interval is empty: the target is absent.
- The algorithm then returns −1; it never scans the whole array.