c++二分查找完整代码
时间: 2023-07-09 21:49:30 浏览: 53
以下是 C++ 中的二分查找完整代码示例:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int target = 5;
int left = 0, right = arr.size() - 1;
int mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (arr[mid] == target) {
cout << "Target found at index " << mid << endl;
return 0;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
cout << "Target not found in the array" << endl;
return 0;
}
```
该示例中,我们定义了一个有序的整数数组 `arr`,并且将要查找的目标值 `target` 设为 5。我们使用左右指针法,定义左指针 `left` 初始值为 0,右指针 `right` 初始值为数组长度减 1,中间指针 `mid` 的初始值为 `(left + right) / 2`。
在 while 循环中,我们使用中间指针 `mid` 来比较目标值 `target` 和数组中间元素的值 `arr[mid]`。如果相等,我们返回找到的结果。如果 `arr[mid] < target`,则说明目标值在右侧,我们将左指针 `left` 更新为 `mid + 1`。否则,目标值在左侧,我们将右指针 `right` 更新为 `mid - 1`。
如果 while 循环结束后仍然没有找到目标值,我们输出 "Target not found in the array"。