Basics
You are given a sorted array of length . Your goal is to find an element in this array. Assume for now that consists of distinct elements, and that is guranteed to exist in .
Here’s how binary search solves this problem. We maintain two variables and that are initially and respectively. represents the range of indices in where could lie.
Next, we compute . Notice that and are both roughly half the size of . The key observation to make here is that we can quickly determine if it is impossible for to be part of a range. Specifically, if is a range and or , then we know that it’s impossible for to be in this range.
We check whether is . If this is true, we know that cannot lie beyond , and so must lie in . On the other hand, if this wasn’t true, i.e., , would have to lie in .
We can keep dividing our search space in half until it only consists of one index, at which point we will know that .
Implementation
Here’s how this is implemented:
int l = 0, r = n - 1;
while (l < r) {
int m = std::midpoint(l, r);
if (A[m] >= x) {
r = m;
} else {
l = m + 1;
}
}
std::cout << x << " is located at index " << l << '\n';Time complexity: .
There exists a very popular alternative implementation of binary search that is prefered by some people. Here, the question in hand is a rephrased version of the original one: find the smallest index such that (notice that both questions are indeed equivalent).
Alternative implementation
int l = 0, r = n - 1;
int ans = n - 1;
while (l <= r) {
int m = std::midpoint(l, r);
if (A[m] >= x) {
ans = m;
r = m - 1;
} else {
l = m + 1;
}
}
std::cout << x << " is located at index " << l << '\n';