Binary Search
Halve the window every step. Requires sorted input, the visualizer will tell you when yours isn't.
Halve the window every step. Requires sorted input, the visualizer will tell you when yours isn't.
step 1 / 6
What's happening
Search window starts as [0, 9], the whole array. Target: 23.
The window [low, high] is the only region where the target can still live. Every comparison provably empties half of it, that's the entire algorithm. Duplicates: this returns one matching index, not necessarily the first.
Understand the algorithm
What it is
Binary search finds a target in a SORTED array by repeatedly comparing the middle element and discarding the half that cannot contain it.
Why it matters
It is the poster child of logarithmic thinking: each comparison halves the remaining work, so a million sorted elements need at most about 20 comparisons. The divide-and-conquer discipline it teaches, maintain an invariant window, shrink it, prove it, recurs throughout computer science.
How it works
- 1Keep a window [low, high] that provably contains the target (if it exists).
- 2Compute the middle: mid = (low + high) / 2, floored.
- 3Compare arr[mid] with the target: equal → found; smaller → search right half; larger → search left half.
- 4The window halves each step; when low > high, the target is absent.
Real-world uses
- Dictionary and phone-book lookups
- Version-control bisection to find the commit that introduced a bug
- Answering 'first index where…' questions over sorted data
- The backbone of many library routines (lower_bound, bsearch)
Strengths
- O(log n), doubling the data adds just one comparison
- O(1) space in its iterative form
- Predictable, input-independent step count
Limitations
- Requires sorted data, sorting first costs O(n log n)
- Random access needed: useless on linked lists
- Notoriously easy to implement with off-by-one bugs (the (low+high)/2 overflow is famous)
Try an unsorted input to see the sorted-requirement explanation.