Binary Search
1Introduction
This lecture explains binary search on an array sorted in nondecreasing order by means of a search-interval invariant. Linear search compares elements in sequence. Binary search instead uses the sorted order to exclude one part of the candidate interval with each comparison.
2Problem specification
Let be an array of elements satisfying
Thus, the array is sorted in nondecreasing order. Given a target , the algorithm returns an index satisfying if such an index exists, and otherwise reports absence.
Duplicate elements are allowed. If occurs at multiple indices, this algorithm may return any one of them; it does not promise the first or last occurrence.
3Half-open interval and midpoint
Represent the candidate indices by the half-open interval . It contains but not , and its length is . When , define
Then , so lies in the current candidate interval.
4Invariant
At the start of every iteration, maintain the following condition:
If occurs in the array, an index satisfying occurs in .
4.1Initialization
Set and . The candidate interval contains the entire array, so the invariant holds.
4.2Preservation
Under , compute the midpoint and compare with .
- If , return and terminate.
- If , sortedness gives for every . Hence no matching index lies in , and the update is valid.
- If , sortedness gives for every . Hence no matching index lies in , and the update is valid.
In either update, every index that can still match remains in the new candidate interval. The invariant is therefore preserved.
4.3Termination condition
When , the candidate interval is empty. If occurred in the array, the invariant would require a matching index in this empty interval, which is impossible. Thus is absent, and the algorithm may report absence.
5Termination
Let be the interval length before an update. After , the new length is ; after , it is . Since , both cases satisfy .
Consequently, the nonnegative integer interval length decreases strictly at every iteration that does not terminate with a match. The algorithm must therefore terminate after finitely many iterations.
6Complexity
After one update, the new interval length satisfies
If , the loop performs no iterations. If , then after updates its length is at most . Once , the interval is empty, so the algorithm performs at most iterations. Its time complexity is , and its auxiliary-space complexity is .
7Algorithm summary
- Set .
- While , compute .
- If , return . If , set ; if , set .
- If , report absence.
The correctness of binary search follows from candidate exclusion justified by sortedness, preservation of the invariant, and strict decrease of the interval length.