第一种
//Arr[]存储数,n表示数组长度,e表示被查找元
//[0,n)
int bin_find(int *Arr, int n, int e)
{
int left, right, mid;
left = 0,right = n; //[0,n)
while(left < right)
{
mid = left + (right - left)/2;
if (Arr[mid] > e)
right = mid; //搜索区间右端为开,right = mid-1会漏掉mid-1处元素
else if (Arr[mid] < e)
left = mid+1;
else
return mid;
}
return -1;
}
第二种
//(-1,n)
//可以找到元素的第一个,不过时间稍差,算法稳定,运行时间只与搜索数组长度有关,而与数组元素分布无关
int bin_find(int *Arr, int n, int e)
{
int left = -1, right = n, mid; //(-1,n)
while(left + 1 != right) //搜索到目标子数组剩一个元素
{
mid = left + (right - left)/2;
if(Arr[mid] < e)
left = mid;
else
right = mid;
}
if(right >= n || Arr[right] != e)
right = -1;
return right;
}
第三种
//[0,n-1]
//Arr[]存储数,n表示数组长度,e表示被查找元
int bin_find(int *Arr, int n, int e)
{
int left, right, mid;
left = 0,right = n-1; //[0,n-1]
while(left <= right)
{
mid = left + (right - left)/2;
if (Arr[mid] > e) //找到目标元素即停止
right = mid-1;
else if (Arr[mid] < e)
left = mid+1;
else
return mid;
}
return -1;
}