对于目标值tag,目标数组中未出现该目标值是,一定会有board[i]<tag<board[j]或者tag<board[0]或者tag>board[size-1]
1.明白二分查找循环条件beg<=end,即:未找到tag时,beg>end不再循环;
2.整个 二分查找过程,都在缩小tag所在的区间范围,end=mod-1或者beg=mod+1,故最后tag其实就在end~beg之间;
代码实现:
P.ans_beg = beg;//一开始就给ans_beg和ans_end赋值为end和beg
P.ans_end = end;
while (beg <= end)
{
mod = (beg + end) / 2;
if(tag==a[mod])
{
P.ans_beg = P.ans_end = mod;
break;
}
else if (tag > a[mod])
{
beg = P.ans_beg = mod + 1;//ans_beg就是beg
}
else end = P.ans_end = mod - 1;//ans_end就是end
}
cout <<P.ans_end+1<< "->" <<P.ans_beg+1 << endl;
//循环结束时beg>end
还有个差不多的,在循环结束以后再给ans_beg和ans_end赋值
while (beg <= end)
{
mod = (beg + end) / 2;
if (a[mod] == tag)
break;
else if (a[mod] > tag)
end = mod - 1;
else beg = mod + 1;
}
if (beg <= end)//找到tag跳出循环
P.ans_end = P.ans_beg = mod;
else
/*最后一次循环的时候,可以肯定的是mod=beg=end;
才会有不管是end=mod-1还是beg=mod+1,都会使得beg>end*/
if(a[mod]>tag)//end=mod-1;
{
P.ans_beg = mod - 1;
P.ans_end = mod;
}
else//beg=mod+1;
{
P.ans_beg = mod;
P.ans_end = mod + 1;
}
笔记到此结束啦!hhhhh!!