Binary search finds an element in a sorted array by repeatedly halving the search space. Compare the target to the middle element — if smaller, search the left half; if larger, search the right half. It's O(log n): searching 1 billion items takes only ~30 comparisons.

How Binary Search Works

Looking up a word in a dictionary: you don't read every page. You open to the middle, see if your word comes before or after, then search the appropriate half. Binary search works the same way on any sorted data.

Binary search requires sorted data. If your data isn't sorted, sort it first (O(n log n)) or use a hash table (O(1) lookup). Binary search is also used in git bisect to find the commit that introduced a bug.

Key Concepts

  • Sorted Input — Binary search only works on sorted data — sort first if needed
  • O(log n) — Each step eliminates half the remaining elements — extremely efficient for large datasets
  • Search Space Halving — Compare target to middle element, discard the irrelevant half, repeat

Learn Binary Search — Top Videos

Binary Search Educators

Frequently Asked Questions

When should I use binary search?

When searching sorted data. Also useful for 'finding the boundary' problems — the smallest value that satisfies a condition (binary search on the answer space).