Lesson 8 of 86BeginnerFree Interactive Lesson

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

MetricComplexity
Time ComplexityO(log n)
Space ComplexityO(1) iterative
Topic ChapterChapter 2: Arrays & Binary Search
Difficulty LevelBeginner

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.

Unlock the full course

All 86 lessons across 15 chapters

View pricing

Delete account

This permanently deletes your account and ends any Pro access.