int binarySearch1(vector<int>a, int target)//循环实现
{
int left = 0;
int right = a.size()-1;
while (left<=right) {
//如果这里的while不用等号的话会导致找不到最左端的|最右端的值
int mid = (left + right) / 2;
if (a[mid] == target) return mid;
else if (a[mid] < target) {
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
};
测试案例: