#include <iostream>
#include <vector>
using namespace std;
int binarySearch(const vector<int>&, const int);
int main() {
vector<int> a = {0, 1, 2, 3, 4, 5};
cout << binarySearch(a, 4);//输出4
return 0;
}
/*
* 初始化 lo 为0,hi 为查找数组的长度,mid 为 lo 和 hi 的平均数
* 当 lo < hi 时进行迭代,如果 mid 处的值小于目标值,则将 lo 更新为 mid + 1;
* 若 mid 处的值大于目标值,将 hi 更新为 mid 进行下一轮迭代
*/
int binarySearch(const vector<int>& v, const int target) {
int lo = 0, hi = v.size();
while (lo < hi) {
//避免 lo + hi 的结果溢出
int mid = lo + (hi - lo) >> 1;
if (v[mid] == target)
return mid;
else if (v[mid] < target)
lo = mid + 1;
else
hi = mid;
}
return -1;//查找失败
}