Abstract
Avoid Overflow
Intuitively, we usually use
(right+left)/2to find the mid point, butright+leftis risky to Integer Overflow.We can avoid this by using
left + (right-left)/2.Proof: let left be and right be ,
Array contains duplicate values
We are unable to determine the index of the target value if the elements in the given array aren’t unique. But we are still able to determine the first & last appearance of this particular value, see First Bad Version.
Handling Boundaries
Right Boundary Includes last Element (左闭右闭)
// Assuming nums is an array
// Setting the right boundary [left, right]
int right = nums.length-1;
// The while loop
while (left<=right){...}
// The shrinking of the range
left = mid+1; // When target is bigger
right = mid-1; // When target is smaller- The right boundary includes the index of an element of the array
Why
left<=rightand notleft<rightFor
while (left<right){ ... }, the loop exits whenleft>=right, we may potentially miss an element which may be the desired value. Sincerightpoints to an valid index of the array.
Important
Setting the boundary for
leftandrightalso depends on the question.Binary search is generally used on index range. For questions like “Kth Smallest Element in a Sorted Matrix” where
midis the potential answer, we setright = midand break the while loop whenleft == right, sinceleft == rightis the answer. We are using binary search on number range.We can use binary search to search for a value in a 2D matrix, given that each row is sorted in non-decreasing order and the first integer of each row is greater than the last integer of the previous row. This approach utilises creative row and column indexing, where binary search is applied to the index range.
Right Boundary Excludes last Element (左闭右开)
// Assuming nums is an array
// Setting the right boundary [left, right)
int right = nums.length;
// The while loop
while (left<right){...}
// The shrinking of the range
left = mid+1; // When target is bigger
right = mid; // When target is smaller- The right boundary excludes the index of an element of the array
Why
left<rightand notleft<=rightFor
while (left<=right){ ... }, the loop exits whenleft>right, we will obtain a mid point that isnums.lengthwhen desired value is bigger than all of the values inside the array. Andarray[nums.length]will result in anindexOutRangeerror.
Hidden Power
- We can use binary search in optimisation problems, not just finding an element inside Array
Abstract
Assume we have a monotonic function
f(x). The output off(x)is proportional to its inputx. That means the bigger the value ofx, the smaller the output off(x)or the bigger the value ofx, the bigger the output off(x). If we want to find the maximum/minimum value ofxsuch that the output off(x)is>=a constant value , we can make use of binary search!The is the smallest value for
xand is biggest value forx, the value ofxacts as the index, and the output off(x)acts as the value at that particular index.
Beer Feast Problem 🍻
We are having a beer feast for a group of guests. We have a total supply of 180 mugs of beers. Let
xbe the number of beers we provide to the guests. We have this magical functionf(x)which calculates a consciousness score of the guests based on the number of beers we give.xis inversely proportional to the consciousness score, this means the more beer we give the less conscious guests get.We want to know what is the maximum number of beers we can give and the guests can still maintain at least 50% consciousness.
f(180)returns 0% consciousness andf(0)returns 100% consciousness.We can make use of binary search to obtain the answer in . The is 0 beer and is 180 beers. We record down the value of
midand when thef(mid)is above 50% consciousness and whenf(mid)is below 50% consciousness. Whenf(mid)gives 50%, the correspondingmidvalue is the the sweet spot for number of beers we can provide. If there isn’t a sweet spot, the maximum value of all themidvalues recorded is the answer.
