left <= right这个地方至于为什么要有等于号,自己去白纸上写两组奇数组和偶数组即可想明白
二分查找三个元素
1.left
2.right
3.middle
代码如下
/*
在一个有序无重复数组nums里中找一个元素target
如果找到就返回其对应下标,找不到就返回-1
int target = 2;//target为要查找的元素
vector<int> nums = {1,2,3,4,7,9,10};
*/
#include <iostream>
#include <vector>
using namespace std;
int main()
{
system("color f5");
int target;//target为要查找的元素
cin >> target;
int n;
cin >> n;
vector<int> nums(n);
//希望输出的结果为 1
for (int i = 0; i < n; i++) {
cin >> nums[i];
}
int left = 0;
int right = nums.size() - 1;
while (left <= right) {
int middle = left + (right - left)/2;
if (nums[middle] > target) {
right = middle - 1;
} else if (nums[middle] < target) {
left = middle + 1;
} else if (nums[middle] == target) {
cout << middle << endl;
break;
} else if (nums[middle] == target) {
cout << "-1" << endl;
break;
}
}
system("pause");
return 0;
}