When you look up a word in a dictionary, you do not leaf through it from the first page: you open the book in the middle, see which side the word is on and throw away the unneeded half. Binary search is built on this idea: at every step the search range is cut in half, so $10^6$ elements need no more than 20 comparisons.
The algorithm is simple, yet $\pm 1$ errors and infinite loops are most common right here. Below we cover the classic version, the ready-made functions and the olympiad favourite — binary search on the answer.
1. The idea and the invariant
The array must be sorted. Two boundaries, lo and hi, keep one rule (the invariant): if $x$ is in the array, it lies in the range $[lo, hi]$. If a[mid] is less than $x$ we drop the left half, if greater, the right half. If the range becomes empty ($lo > hi$), $x$ is not there.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, q;
cin >> n >> q;
vector<int> a(n);
for (int &x : a) cin >> x; // the array is sorted in ascending order
while (q--) {
int x;
cin >> x;
int lo = 0, hi = n - 1, ans = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2; // (lo + hi) / 2 can overflow
if (a[mid] == x) { ans = mid; break; }
if (a[mid] < x) lo = mid + 1; // x is in the right half
else hi = mid - 1; // x is in the left half
}
cout << ans << "\n";
}
}
For 7 3, the array 1 3 5 7 9 11 13 and the queries 7 4 13 the program prints 3, -1, 6. Each query takes $O(\log N)$ time.
2. Off-by-one traps
Almost every bug comes from the boundaries. On a closed range $[lo, hi]$ the loop runs while lo <= hi; on a half-open $[lo, hi)$ it runs while lo < hi with hi = mid. Pick one style and never mix them.
- Overflow: for numbers around $10^9$ the sum
lo + hiexceeds theintlimit ($\approx 2.1 \cdot 10^9$), which is why we writelo + (hi - lo) / 2. - Infinite loop: if a
lo < hiloop doeslo = mid, thenmidmust round up:lo + (hi - lo + 1) / 2. Otherwise, once $hi = lo + 1$,midalways equalslo. - An unsorted array: the program does not crash, it silently returns a wrong answer.
3. lower_bound, upper_bound and bisect
Often you need not a yes/no answer but a boundary. lower_bound finds the first element not less than $x$, and upper_bound the first element greater than $x$. Their difference is how many times $x$ occurs.
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> a = {1, 2, 2, 2, 5, 7};
auto l = lower_bound(a.begin(), a.end(), 2); // first a[i] >= 2
auto r = upper_bound(a.begin(), a.end(), 2); // first a[i] > 2
cout << (l - a.begin()) << " " << (r - a.begin()) << " " << (r - l) << "\n"; // 1 4 3
}
In Python the bisect module does the same job:
from bisect import bisect_left, bisect_right
a = [1, 2, 2, 2, 5, 7]
l, r = bisect_left(a, 2), bisect_right(a, 2)
print(l, r, r - l) # 1 4 3
A subtlety: for std::set call the member function s.lower_bound(x). The generic std::lower_bound advances its iterator one step at a time and runs in $O(N)$ there.
4. Binary search on the answer
Here we search not for an array element but for the answer itself. There is one condition: the check function can(d) must be monotonic, looking like true, ..., true, false, ..., false.
The classic problem: place $C$ cows in $N$ stalls so that the distance between the two closest ones is as large as possible. We check can(d) greedily in $O(N)$: put each cow in the first stall at least $d$ away from the previous one. If distance $d$ is achievable, so is any smaller one — that is the monotonicity.
#include <bits/stdc++.h>
using namespace std;
int n, c;
vector<long long> p;
// Can c cows be placed at least d apart?
bool can(long long d) {
int cnt = 1;
long long last = p[0];
for (int i = 1; i < n; i++)
if (p[i] - last >= d) { cnt++; last = p[i]; }
return cnt >= c;
}
int main() {
cin >> n >> c;
p.resize(n);
for (auto &x : p) cin >> x;
sort(p.begin(), p.end());
long long lo = 0, hi = p[n - 1] - p[0]; // can(0) is always true
while (lo < hi) {
long long mid = lo + (hi - lo + 1) / 2; // round up
if (can(mid)) lo = mid;
else hi = mid - 1;
}
cout << lo << "\n";
}
For 5 3 and 1 2 8 4 9 the answer is 3 (cows at 1, 4 and 8). The complexity is $O(N \log M)$, where $M$ is the range of the coordinates. Whenever a statement says "maximise the minimum" or "minimise the maximum", try this technique.
Conclusion
Binary search on sorted data costs $O(\log N)$ per query. Reinforce what you have learnt with the search problems and practise every day with the daily problem!