用c++写一个二分查找
时间: 2023-07-19 10:34:47 浏览: 46
好的,下面是一个简单的二分查找的 C++ 实现:
```c++
#include <iostream>
using namespace std;
int binarySearch(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(arr) / sizeof(int);
int target = 6;
int result = binarySearch(arr, n, target);
if (result == -1) {
cout << "Element not found." << endl;
} else {
cout << "Element found at index: " << result << endl;
}
return 0;
}
```
该程序首先定义了一个 `binarySearch` 函数,它接受一个数组、数组的长度和要查找的目标值作为参数。函数通过维护左右指针的方式来实现二分查找,最终返回目标值在数组中的下标。如果目标值不存在,则返回 -1。
在 `main` 函数中,我们定义了一个整型数组和目标值,然后调用 `binarySearch` 函数进行查找。最终输出查找结果。
希望这个简单的示例能够帮助你理解二分查找的实现方式。