记录二分查找的递归和非递归实现
递归
Status binarySearch(int *arr,int low,int high,int key){
int mid;
if(low<=high){
mid=(low+high)/2;
if(arr[mid]==key){
return OK;
}
if(arr[mid]>key){
return binarySearch(arr,low,mid-1,key);
}
if(arr[mid]<key){
return binarySearch(arr,mid+1,high,key);
}
}else{
return ERROR;
}
}
非递归
Status binarySearch(int *arr,int low,int high,int key){
int mid;
while(low<=high){
mid = (low+high)/2;
if (arr[mid]==key)
return OK;
if(arr[mid]>key)
high=mid-1;
if(arr[mid]<key)
low=mid+1;
}
return ERROR;
}