Binary search, explained

Find anything in a sorted array by halving the search space, lo, hi and mid pointers animated.

Binary search only works on sorted data, and that's its superpower. Check the middle element: if your target is smaller, the whole right half is irrelevant; if bigger, the left half is. Either way, one comparison just deleted half the problem.

Keep halving and even huge arrays fall fast: a billion sorted items need about 30 comparisons. It's the reason 'keep it sorted' is one of the oldest performance tricks in computing.

Remember this

  • Requires sorted input, that's the deal
  • Each comparison halves the search space: O(log n)
  • A billion items ≈ 30 comparisons

Got a different question? SeaThru generates a fresh video for any topic where systems talk or data structures move.

Ask your own question →

Keep learning