用二分查找法寻找升序数组目标元素的下标
#include <iostream>
using namespace std;
int main(void)
{
int search, n; //search为目标元素,n为数组元素个数
cin >> search >> n ;
int *a = new int[n]; //创建长度为n的动态数组
for (int i = 0; i < n; i++) {
cin >> a[i]; //存储数组元素
}
int m, flag=0 ; //flag用于标记数组内是否有目标元素
int l = 0, r = n - 1;
m = (l + r) / 2; //寻找中间元素的下标
do {
if (a[m] == search) {
cout << m << endl;
break;
}
else if (a[m] < search) {
l = m + 1;
m = (l + r) / 2;
if (l > r) {
flag = 1;
break;
}
}
else if (a[m] > search) {
r = m - 1; //
m = (l + r) / 2;
if (l > r) {
flag = 1;
break;
}
}
} while (1);
if (flag == 1) {
cout << "不存在" << endl;
}
delete[]a;
return 0;
}