二分查找
定义
对已经排好序的数组进行查找
对数组进行操作
在查找失败最多次数$ K=\lfloor log2^{n}\rfloor +1 $(向下取整加一)
二分查找的时间复杂度:$ \displaystyle\frac{n}{2^k} = 1,K = log2^n $
由于简书不可以读取latex公式,这里推荐到我的主页去看。请点击!
二分查找的代码
int BinaryChop(int Num[],int nCount,int nValue)
{
int max_index = nCount-1;
int min_index = 0;
int Mid = 0;
while (min_index<=max_index)
{
Mid = (max_index+min_index)/2;
if(Num[Mid] == nValue)
return Mid;
if(Num[Mid]>nValue)
{
max_index = Mid-1;
}else
{
min_index = Mid+1;
}
}
return -1;
}