递归版本
int binarySearch(int i, int j,int *a, int find)
{
int m;
if(i == j)
{
if(a[i] == find)
return i;
else
return -1; //can't find this number in the array
}
else
{
m = (i+j)/2;
if(a[m] < find)
{
cout << "大于中间数"<<a[m]<<endl;
return binarySearch(m+1,j,a,find);
}
else
{
cout << "小于等于中间数"<<a[m]<<endl;
return binarySearch(i,m,a,find);
}
}
}
非递归版本
int BinarySearch(int begin, int end, int* a, int find)
{
int m;
while(1)
{
if(begin > end)
{
return -1;
}
else
{
m = (begin + end)/2;
if(a[m] == find)
{
return m;
}
else if(a[m] < find)
{
begin = m + 1;
}
else
{
end = m - 1;
}
}
}
}
二分查找得到刚好比起大的数:
int binarysearch(int start, int end, int find, int* a)
{
int mid;
if(start == end)
return end;
else
{
mid = (start + end)/2;
if(find <= a[mid])
return(binarysearch(start,mid,find,a));
else
return(binarysearch(mid+1,end,find,a));
}
}
二分查找得到刚好比其小的数
int BinarySearch(int begin, int end, int find, int *a)
{
int m;
while(1)
{
if(begin == end)
{
return begin;
}
else
{
m = (begin + end)/2 + 1;
if(a[m] > find)
{
end = m - 1;
}
else
{
begin = m;
}
}
}
}