二分查找是一种比较基础的查找方法,主要分为递归和非递归两种方式。
非递归版本:
int BinarySearch(vector<int> A,int n,int val)
{
int low,high,mid;
if(A.empty()||n==0)
return -1;
low = 0;
high = n;
while(low<=high)
{
mid = (low + high)/2;
if(A[mid]==val)
return mid;
else if(A[mid]<val)
low = mid+1;
else
high = mid-1;
}
return -1;
}
递归版本:
int BinarySearch(vector<int> A,int val,int low,int high)
{
if(low<=high){
mid = (low + high)/2;
if(A[mid]==val)
return mid;
else if(A[mid]<val)
return BinarySearch(A,val,mid+1,high);
else
return BinarySearch(A,val,low,mid-1);
}
else
return -1;
}