int Binary(int a[],int low,int high,int k)
{
int mid;
if(low<=high)
{
mid=(low+high)/2;
if(a[mid]==k)
return mid;
else if(a[mid]<k)
return Binary(a,mid+1,high,k);
else
return Binary(a,low,mid-1,k);
}
else
return -1;
}
时间复杂度O(log2n)
非递归
int BinSearch(int a[],int n,int k){
int low=0,high=n-1,mid;
while(low<=high){
mid=(low+high)/2;
if(a[mid]==k)
return mid;
if(a[mid]>k)
high=mid-1; //左半区间
else
low=mid+1; //右半区间
}
return -1;
}