Binary Search
Compare with the middle of a sorted array and half of it stops mattering.
Decision · step 3 of 6Binary Search: Target on the right
16 is smaller than 56, so 56 can only be to the right. Discard 5 values.
What you will see
MIDDLE -> COMPARE -> DISCARD HALF -> REPEAT; discarded cells recede, the active range contracts.
Cost
| Best | O(1) |
|---|---|
| Average | O(log n) |
| Worst | O(log n) |
| Space | O(1) |
Recursive form uses O(log n) stack space.
How you work with it here
play it through, step one change at a time, scrub to any step, run it on your own input, predict what happens next.
Screen readers: Cells announce index, value and state (current, discarded, found); each step announces the comparison and the resulting range.
Reduced motion: Range and pointer changes snap into place with a short crossfade; discarded cells fade without movement.
Before this
Variants
- Lower Bound First index whose value is >= target.
- Upper Bound First index whose value is > target.
- First Occurrence Lower bound
- Last Occurrence Upper bound minus one