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/, 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/. The algorithm stops when n/ ≤ 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:
- 1Set the interval size after k steps to n/
- 2Require n/ ≤ 1 for termination
- 3Solve for k to obtain k ≥ log₂ n
Steps needed for different array sizes:
| Array size n | Worst‑case comparisons |
|---|---|
| 16 | 4 |
| 64 | 6 |
| 256 | 8 |
| 1024 | 10 |
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 itNo account needed to try it.
What people ask next
- How does binary search compare to linear search in terms of time complexity?Ask
- Why is O(log n) considered optimal for comparison‑based search?Ask
- What happens to binary search if the array is not sorted?Ask
- what does Big O notation actually measure
- what is a race condition
- why are hash table lookups O(1)
- what is the difference between a stack and a queue
