C++ 实现二分查找
时间: 2023-12-01 13:41:19 浏览: 75
以下是C++实现二分查找的代码示例:
```cpp
#include <iostream>
using namespace std;
int binarySearch(int arr[], int left, int right, int x) {
while (left <= right) {
int mid = left + (right - left) / 2;
// 如果 x 在中间
if (arr[mid] == x)
return mid;
// 如果 x 大于中间元素,则在右侧子数组中查找
if (arr[mid] < x)
left = mid + 1;
// 如果 x 小于中间元素,则在左侧子数组中查找
else
right = mid - 1;
}
// 如果未找到 x,则返回 -1
return -1;
}
int main() {
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
```
阅读全文