Binary Search, explained step by step

Binary Search is a highly efficient search algorithm that finds the position of a target value within a sorted array. Instead of scanning one by one, it works by repeatedly dividing the search space in half. It compares the target to the middle element: if the target is smaller, it completely discards the right half; if it is larger, it discards the left half. This halving makes it incredibly fast, even for massive datasets.

Intuition: Like finding a word in a dictionary — you open to the middle, check if your word is before or after, and eliminate half the book.

How it works

  1. Initialize two pointers: low (start) and high (end) of the array.
  2. Calculate the mid index: mid = low + (high - low) / 2.
  3. Compare the middle element with the target value.
  4. If it matches, return the mid index.
  5. If the target is smaller, search the left half (high = mid - 1).
  6. If the target is larger, search the right half (low = mid + 1). Repeat until low > high.

Complexity

  • Best: O(1)
  • Average: O(log n)
  • Worst: O(log n)
  • Space: O(1)
  • Stable: yes

When to use it

Sorted arrays when O(log n) search time is needed. Foundation for many advanced algorithms.

Interview questions

  • Why must the array be sorted for Binary Search?
  • Why use mid = low + (high-low)/2 instead of (low+high)/2?
  • What is the iterative vs recursive complexity of Binary Search?
  • How would you find the first or last occurrence of a duplicate?

Compare Binary Search

Open Binary Search in the visualiser