Binary Search on a Sorted Array
Compare the target with the middle value and keep only the side that could still contain it.
Core Intuition & How It Works
Binary search locates a target in a sorted array by inspecting the middle element and eliminating half of the remaining range on each step. Repeated halving reduces search time from O(n) to O(log n).
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(log n) |
| Space Complexity | O(1) iterative |
| Topic Chapter | Chapter 2: Arrays & Binary Search |
| Difficulty Level | Beginner |
Key Pattern to Recognize
Maintain a clear loop invariant—either closed [lo, hi] or half-open [lo, hi)—and shrink the interval strictly every iteration.
Common Pitfalls & Edge Cases
Infinite loops from wrong mid rounding or boundary updates, and integer overflow when computing (lo + hi) / 2 in fixed-width integers.
Real-World & Technical Interview Applications
Sorted database indexes, version bisection (git bisect), lower/upper bound queries, and dictionary lookups.