循环写法
int binary_search(vector<int> list,int n) {
int low = 0;
int high = list.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
int guess = list[mid];
if (guess > n)
high = mid - 1;
else if (guess < n)
low = mid + 1;
else if (guess == n)
return mid;
}
return NULL;
}
void test02()
{
vector<int> v = { 1,2,3,4,5 };
cout<<binary_search(v, 2);
}
递归写法
bool binary_search(vector<int> list,int begin, int end, int target) {
if (begin > end)
return false;
int mid = (begin + end) / 2;
if (target == list[mid])
return mid;
else if (target < list[mid]) //向左区间寻找
return binary_search(list, begin, mid - 1, target);
else if (target > list[mid]) //向右区间寻找
return binary_search(list, mid + 1, end, target);
}
void test02()
{
vector<int> v = { 1,2,3,4,5 };
cout<<binary_search(v, 0,4,1);
}