递归实现
template<typename T>
int binary_search2(const T arr[], const int left, const int right, const T key)
{
if (NULL == arr || nullptr == arr || 0 > left || 0 > right)
return -1;
if (left > right)
return -2;
int mid = (left + right) / 2;
if (0 < mid)
{
if (key == arr[mid])
return mid;
else if (key > arr[mid])
return binary_search2(arr, mid + 1, right, key);
else
return binary_search2(arr, left, mid - 1, key);
}
// 已经越界,说明已经找不到了
else
return -3;
}
非递归实现
template<typename T>
int binary_search(T arr[], int len, const T find)
{
// 参数检查
if (0 == len || nullptr == arr || NULL == arr || 0 > len)
return -1;
int low = 0;
int high = len - 1;
while (low < high)
{
// 找到中间值
int mid = (high + low) / 2;
if (0 <= mid)
{
if (arr[mid] == find)
return mid;
else if (arr[mid] > find)
high = mid - 1;
else
low = mid + 1;
}
else
break;
}
return -2;
}