Binary Search Algorithm


Binary Search Algorithm

Simon
Binary search is one of the most important algorithms out there. It lets you quickly find a target value in a sorted array, or look up a word in a dictionary.

Maria
It sounds simple, but I've heard it's surprisingly easy to get wrong. A 1988 study found that only one in four textbooks had a correct implementation.

Simon
Right, and even Java's own library had a bug that went unnoticed for over nine years. The issue was an overflow in calculating the middle index. So let's start from the basics and build up carefully.

Maria
So how does the algorithm work? Say we have a sorted array of size 7, indices 0 to 6, and we're looking for the target value 10.

Simon
We look at the middle element. If it's equal to the target, we're done. Otherwise, we eliminate half the array. For example, if the middle is 6 and target is 10, since the array is sorted, 10 must be to the right. So we focus on indices 4 to 6, and repeat.

Maria
And eventually you either find 10 at index 5, or if the target isn't there, the search range becomes empty and we return -1.

Simon
Exactly. But the tricky part is computing the middle index. A lot of people use (L+R)/2, but that can overflow if L and R are large integers. In languages like C++ or Java, int holds up to about 2 billion, and adding two such values overflows.

Maria
So what's the safe formula? I've seen L + (R-L)/2.

Simon
Right. Since R >= L, the difference R-L fits in the type. Then we do L + (R-L)/2, which avoids overflow. In C++ and Java, integer division automatically floors. In Python, you'd use double slash.

Maria
Let's see the pseudocode: initial range is from 0 to n-1. While Left <= Right, we compute mid = L + (R-L)/2. If a[mid] equals target, return mid. Otherwise, if target is greater, we set L = mid+1, else set R = mid-1. If we exit the loop, return -1.

Simon
That's the classic version. But binary search isn't limited to finding an exact match. For example, suppose we have an array and want the first value that is >= X. That's called lower bound.

Maria
I can see why the simple approach wouldn't work. If we find an element that's >= X, we can't just return it, because there might be a smaller one to the left.

Simon
Exactly. So we keep an extra variable ans, initially a sentinel like -1 or infinity. When we see a[mid] >= X, we update ans to mid and then search left for a possibly better one by setting R = mid-1. If a[mid] < X, we search right by setting L = mid+1.

Maria
So that way we find the leftmost index satisfying the condition. And if no such element exists, ans remains the sentinel.

Simon
Right. This pattern of 'first true' in a sequence of falses then trues is key. You can also find the last true by mirroring the logic. The key is to think in terms of a predicate that is false for a prefix and true for a suffix, or vice versa.

Maria
Like in the rotated array problem. We have a sorted array that's been rotated, and we want the smallest element. The challenge is that the array isn't fully sorted.

Simon
But we can still use binary search. Consider the array [6,7,...,19,2,3]. The split is between the larger numbers from the original suffix and the smaller ones from the original prefix. If we compare each element with the last element, say a[mid] > a[last], then it belongs to the left part; otherwise it's in the right part.

Maria
So we look for the first false when comparing with the last element. That gives us the start of the smaller part, which is the minimum.

Simon
Exactly. In general, binary search works as long as you can split the array into two parts based on a condition. Another example is finding a peak: an element that is larger than its neighbors. The array increases then decreases. We can check if a[mid] > a[mid-1] (treating a[-1] as -infinity) and look for the last true.

Maria
And binary search also works on real numbers. To find the square root of 2, we can search in [0,2], check mid^2 against 2, and narrow down until the interval is small enough.

Simon
Right. With floats, we don't have integer indices, so we just set L = mid or R = mid depending on the comparison, and stop when R-L is smaller than the desired precision.

Maria
So to sum up: binary search is a powerful tool for sorted arrays and beyond. The key is to think about the condition that splits the search space and use it to decide which half to explore.

Simon
Exactly. And always use the safe mid formula. Whether you're looking for an exact target, a lower bound, or a peak, the same principles apply. Happy searching!

Ask anything
We've read this whole study set, so questions about it get the best answers.