二分法查找从概念上很好理解,困难的地方在于有几个细节需要注意:
1.循环执行条件。
2.递进方式。
3返回值的问题,返回左右边界值还是返回一个存储结果的中间变量。
以一个最常见的游戏为例,甲从0~9中随便选择一个整数,乙来猜,甲回答大于,小于,或等于,若甲选择的数字为9,则乙在大概率下,最快几次可以猜到。
(0+9)/2 = 4 (0 + 4)/2=2 (0+2)/2=1 (0+1)/2=0 (0+0)/2=0; left = right; result = left;
(0+9)/2 = 4 (5 +9 )/2=7 (5+7)/2=6 (5+6)/2=5 (5+5)/2=5; left = right;result=left;
(0+9)/2 = 4 (4 +9 )/2=6 (6+9)/2=7 (7+9)/2=8 (8+9)/2=8 死循环
最后一种情况进入死循环,可以看出由于整数除法只保留整数位,所以left在每次更新的时候必须等于mid +1;
倘若游戏规则改为甲只能回答小于,大于等于两种
(0+9)/2 = 4 (0 + 4)/2=2 (0+2)/2=1 (0+1)/2=0 (0+0)/2=0; left = right; result = left;
(0+9)/2 = 4 (5 +9 )/2=7 (5+7)/2=6 (5+6)/2=5 (5+5)/2=5; left = right;result=left;
(0+9)/2 = 4 (5 +9 )/2=7 (8+9)/2=8 (9+9)/2=9; left = right; result = left;
倘若游戏规则改为甲只能回答小于等于,大于两种
(0+9)/2 = 4 (0 + 4)/2=2 (0+2)/2=1 (0+1)/2=0 (1+1)/2=1; left = right; result != left;
(0+9)/2 = 4 (5 +9 )/2=7 (5+7)/2=6 (5+6)/2=5 (6+6)/2=6; left = right;result != left;
(0+9)/2 = 4 (5 +9 )/2=7 (8+9)/2=8 (9+9)/2=9; left = right; result = left;
这样会得到错误的结果。
甲只能回答小于等于,大于,乙在进行猜测的时候,right在每次更新的时候right=mid-1.
(0+9)/2 = 4 (0 + 3)/2=1 (0+0)/2=0 left = right; result = left;
(0+9)/2 = 4 (5 +9 )/2=7 (5+6)/2=5 (5+4)/2=4; left>right; result=left
(0+9)/2 = 4 (5 +9 )/2=7 (8+9)/2=8 (9+9)/2=9; left = right; result = left;
此时的情况当甲选择的数字为5时,循环执行的条件应该为left<=right,但如果采用该循环执行条件,当甲选择的数字为9时,可能出现left=10的情况,溢出了,倘若甲回答的是小于,大于等于,那么right会在8和9之间无限反复,程序进入死循环。
所以可以总结出一个最通用的一般格式为:
Int binary_search(int left, int right, int target){
While(left < right){
Mid = (left +right) / 2;
If( mid <= target ){
Left = mid +1;
}else{
Right =mid;
}
}
Return left;
}
以下是两种应用。
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.You may assume no duplicates in the array.
int searchInsert(vector& nums, int target) {
const int n = nums.size();
int left = 0, right = n-1, mid = 0;
if(target > nums[right]){
return right + 1;
}
while(left < right ){
mid = (right + left)/2;
if(nums[mid] < target){
left = mid + 1;
}else{
right = mid;
}
}
return left; }
Implement int sqrt(int x).Compute and return the square root of x.x is guaranteed to be a non-negative integer.
int mySqrt(int x) {
int left = 0, mid = 0,right = x;
int result = 0;
if(x < 2)
return x;
while(left <= right){
mid = (right + left)/2;
if( x / mid > mid){
left = mid + 1;
result = mid;
}else if(x / mid < mid){
right = mid - 1;
}
else{
return mid;
}
}
return result;
}