本人最近懒癌发作,博客已经几个月没动了,突然良心发现自己二分理解的不好,万一要去省赛岂不是要收到来自大神的嘲讽?
二分分为四种,严格大于某值的最小值;严格小于某值的最大值;大于等于某值的最小值;小于等于某值的最大值
我们需要关注三个地方:
1.循环的条件 low<high 因为如果两者相等说明找到了
2.改变边界的方法及条件:满足要求条件的时候对应边界=mid 否则mid+1或者-1
3.mid的取整方法:如果的找大于某值的最小值 向下取整;小于某值的最大值向上取整
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
int Array[7]={2,4,6,8,10,12,14};
int low=0,high=6,mid=3,target=8;
puts("target:8");
puts("> min");
while(low<high)
{
if (Array[mid] > target)//ok
high = mid;
else
low = mid + 1;
mid = (low + high) / 2;
printf("low=%d,mid=%d,high=%d\n",Array[low],Array[mid],Array[high]);
}
printf("%d\n----------------------\n",Array[mid]);
low=0,high=6,mid=3,target=8;
puts("< max");
while(low<high)
{
int flag=-1;
if (Array[mid] < target)//ok
low = mid;
else
high = mid - 1,flag=1;
mid = (low + high+1) / 2;
printf("flag=%d,low=%d,mid=%d,high=%d\n",flag,Array[low],Array[mid],Array[high]);
}
printf("%d\n----------------------\n",Array[mid]);
low=0,high=6,mid=3,target=8;
puts(">= min");
while(low<high)
{
if (Array[mid] >= target)//ok
high = mid;
else
low = mid + 1;
mid = (low + high) / 2;
printf("low=%d,mid=%d,high=%d\n",Array[low],Array[mid],Array[high]);
}
printf("%d\n----------------------\n",Array[mid]);
low=0,high=6,mid=3,target=8;
puts("<= max");
while(low<high)
{
if (Array[mid] <= target)//ok
low = mid;
else
high = mid - 1;
mid = (low + high+1) / 2;
printf("low=%d,mid=%d,high=%d\n",Array[low],Array[mid],Array[high]);
}
printf("%d\n----------------------\n",Array[mid]);
return 0;
}
输出 target:8
> min
low=10,mid=12,high=14
low=10,mid=10,high=12
low=10,mid=10,high=10
10
----------------------
< max
flag=1,low=2,mid=4,high=6
flag=-1,low=4,mid=6,high=6
flag=-1,low=6,mid=6,high=6
6
----------------------
>= min
low=2,mid=4,high=8
low=6,mid=6,high=8
low=8,mid=8,high=8
8
----------------------
<= max
low=8,mid=12,high=14
low=8,mid=10,high=10
low=8,mid=8,high=8
8
----------------------