折半查找完整代码c++
时间: 2023-11-30 12:41:59 浏览: 107
以下是折半查找的完整代码C++实现:
```c++
#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 大于 mid,则在右侧子数组中查找
if (arr[mid] < x)
left = mid + 1;
// 如果 x 小于 mid,则在左侧子数组中查找
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;
}
```
阅读全文