递归版本
int binary_search(const int a[], int low,int up, const int key)
{
int mid=(low+up)/2;
if(low>up)
return -1;
else
{
if(a[mid]==key)
return mid;
else if(a[mid]<key)
return binary_search(a,mid+1,up,key);
else
return binary_search(a,low,mid-1,key);
}
}
非递归版本
int binary_search(const int a[], int low,int up, const int key)
{
int mid;
while(low<=up)
{
mid=(low+up)/2;
if(a[mid]==key)
return mid;
else
(a[mid]<key)?(low=mid+1):(up=mid-1);
}
return -1;
}