The general way to search for an element x in an array is a loop through all elements:
for (int i = 0; i < n; i++) {
if (a[i] == x) {
// x found at index i
}
}
This takes O(n) time, and if the order of the elements is arbitrary, nothing better is possible. But if the array is sorted, the order guides the search: binary search finds an element in O(log n) time.
Method 1
The usual implementation resembles looking for a word in a dictionary. The search keeps an active region lo..hi of the array, at first the whole array. At each step it checks the middle element: if it is x, the search ends; otherwise it continues in the left or the right half, depending on the middle element. The region halves at each step, so the time is O(log n). The program also prints the region of each step:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, x;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i]; // sorted array
cin >> x;
int lo = 0, hi = n - 1, found = -1;
while (lo <= hi) {
int k = (lo + hi) / 2;
cout << "[" << lo << ".." << hi << "] k=" << k << "\n";
if (a[k] == x) {
found = k;
break;
}
if (a[k] > x) hi = k - 1;
else lo = k + 1;
}
cout << found << "\n";
}
10 1 3 4 7 8 10 12 15 18 20 15
Output
[0..9] k=4 [5..9] k=7 7
Method 2
Another implementation goes through the array from left to right with jumps, and slows down near the target. The first jump is n/2, then n/4, n/8 and so on, down to 1. After the jumps either the element is found or it is not in the array. The while loop runs at most twice for each jump length, so the time is O(log n):
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, x;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i]; // sorted array
cin >> x;
int k = 0;
for (int b = n / 2; b >= 1; b /= 2) {
while (k + b < n && a[k + b] <= x) k += b;
cout << "jump " << b << ": k=" << k << "\n";
}
if (a[k] == x) cout << k << "\n";
else cout << -1 << "\n";
}
10 1 3 4 7 8 10 12 15 18 20 15
Output
jump 5: k=5 jump 2: k=7 jump 1: k=7 7
C++ functions
The standard library has functions based on binary search that work in logarithmic time on a sorted array:
lower_bound: the first element whose value is at least x,upper_bound: the first element whose value is larger than x,equal_range: both of them.
They return pointers (iterators); when there is no such element, the pointer is just after the last element. Subtracting the start of the array gives an index, and upper_bound − lower_bound is the number of elements equal to x:
#include <bits/stdc++.h>
using namespace std;
int main() {
int a[] = {1, 2, 4, 4, 4, 7, 9, 9};
int n = 8;
for (int x : {4, 5, 9, 10}) {
auto k = lower_bound(a, a + n, x) - a;
auto l = upper_bound(a, a + n, x) - a;
auto r = equal_range(a, a + n, x);
cout << "x=" << x << ": lower_bound " << k << ", upper_bound " << l
<< ", count " << r.second - r.first;
if (k < n && a[k] == x) cout << ", found at " << k;
cout << "\n";
}
}
Output
x=4: lower_bound 2, upper_bound 5, count 3, found at 2 x=5: lower_bound 5, upper_bound 5, count 0 x=9: lower_bound 6, upper_bound 8, count 2, found at 6 x=10: lower_bound 8, upper_bound 8, count 0
Finding the smallest solution
An important use of binary search is finding where the value of a function changes. Suppose we look for the smallest value k that is a valid solution, and a function ok(x) returns true if x is valid. We know that ok(x) is false for x < k and true for x ≥ k:
| x | 0 | 1 | … | k−1 | k | k+1 | … |
|---|---|---|---|---|---|---|---|
| ok(x) | false | false | … | false | true | true | … |
The search with jumps finds the largest x for which ok(x) is false, so k = x + 1. The first jump z must be large enough, for example a value for which we know that ok(z) is true. The function ok is called O(log z) times, so if it works in O(n), the total time is O(n log z). In the program ok(x) checks x·x ≥ z, so it finds the rounded-up square root of the input:
#include <bits/stdc++.h>
using namespace std;
long long z; // we look for the smallest x with x * x >= z
bool ok(long long x) {
return x * x >= z;
}
int main() {
cin >> z;
long long x = -1;
for (long long b = z; b >= 1; b /= 2) {
while (!ok(x + b)) x += b;
}
long long k = x + 1;
cout << k << "\n";
}
1000
Output
32
Finding the maximum value
Binary search also finds the maximum of a function that first increases and then decreases: a position k with f(x) < f(x+1) for x < k and f(x) > f(x+1) for x ≥ k. We search for the largest x with f(x) < f(x+1), and then k = x + 1. Unlike in ordinary binary search, consecutive values of the function must not be equal, because then we would not know in which direction to continue.
#include <bits/stdc++.h>
using namespace std;
// first increasing, then decreasing; the maximum is at x = 37
long long f(long long x) {
return 5 - (x - 37) * (x - 37);
}
int main() {
long long z = 1000; // the maximum is somewhere in 0..z
long long x = -1;
for (long long b = z; b >= 1; b /= 2) {
while (f(x + b) < f(x + b + 1)) x += b;
}
long long k = x + 1;
cout << "k = " << k << ", f(k) = " << f(k) << "\n";
}
Output
k = 37, f(k) = 5
Based on: Antti Laaksonen, Competitive Programmer's Handbook, section 3.3 (CC BY-NC-SA 4.0). Changed: the text is shortened and adapted, the code fragments are complete programs, and the diagrams, tasks and quizzes are new. Adaptation: Boban Blagojević, CC BY-NC-SA 4.0.