c++二分查找猜数字
时间: 2023-12-26 21:27:06 浏览: 78
以下是两种C++二分查找猜数字的例子:
1. 递归实现二分查找
```cpp
#include <iostream>
using namespace std;
int bs(int left, int right, int x, int a[]) {
int mid = (left + right) / 2;
if (x < a[mid]) {
return bs(left, mid - 1, x, a);
} else if (x > a[mid]) {
return bs(mid + 1, right, x, a);
} else {
return mid;
}
}
int main() {
int n, x;
cin >> n >> x;
int a[105];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
cout << bs(0, n, x, a);
return 0;
}
```
2. 非递归实现二分查找
```cpp
#include <iostream>
using namespace std;
int main() {
int n, x;
cin >> n >> x;
int a[105];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
int head = 0, tail = n;
while (head != tail) {
int mid = (head + tail) / 2;
if (a[mid] > x) {
tail = mid;
continue;
}
if (a[mid] <= x) {
head = mid + 1;
continue;
}
}
cout << head - 1;
return 0;
}
```
阅读全文