Skip to content

Why is binary search O(log n)

Binary search runs in O(log n) because each comparison discards half of the remaining elements, so the number of examined items grows proportionally to the logarithm of the input size. After k steps the interval size is n/2k2^k, and the algorithm stops when this size reaches 1, giving k = ⌈log₂ n⌉.

Computer Science · Algorithm analysis


Binary search repeatedly halves a sorted interval until the target is found or the interval is empty. Because each comparison eliminates half of the remaining elements, the number of elements examined after k steps is n/2k2^k. The algorithm stops when n/2k2^k ≤ 1, which solves to k ≥ log₂ n, giving a worst‑case running time of O(log n).

How the halving works

Assume an array of length n is sorted in ascending order. The algorithm compares the target with the middle element at index ⌊n/2⌋. If the target is smaller, the right half is discarded; otherwise the left half is discarded. This reduction by a factor of two is the core reason for the logarithmic bound.

Consider a sorted array of 1 024 integers and a target value that is not present. First comparison checks the element at index 512, shrinking the interval to 512 elements. Subsequent comparisons reduce the interval to 256, 128, 64, 32, 16, 8, 4, 2, and finally 1, requiring ten comparisons, which equals ⌈log₂1024⌉ = 10.

Key properties that give the logarithmic bound:

  • Each step halves the search space
  • The number of steps is proportional to the exponent needed to reduce n to 1
  • The base of the logarithm is 2
  • The ceiling function makes the step count an integer

To count the steps analytically:

  1. 1Set the interval size after k steps to n/2k2^k
  2. 2Require n/2k2^k ≤ 1 for termination
  3. 3Solve for k to obtain k ≥ log₂ n

Steps needed for different array sizes:

Array size nWorst‑case comparisons
164
646
2568
102410

The base of the logarithm is 2 because the interval is halved each step. Changing the base only multiplies the result by a constant factor, which big‑O notation ignores. The ceiling function ⌈log₂ n⌉ ensures the count is an integer, because you cannot perform a fractional comparison.

Check yourself

What is the number of comparisons binary search makes on an array of 256 elements in the worst case?

Get this as a lesson built for you

Describe what you are studying and Lernex writes the lesson and the questions around it. Free, and it takes about a minute.

Try it

No account needed to try it.

What people ask next