递归实现二分法c++
时间: 2023-12-02 15:42:56 浏览: 89
以下是递归实现二分法的C++代码示例:
```c++
#include <iostream>
using namespace std;
int binarySearch(int arr[], int start, int ends, int target) {
if (ends >= start) {
int mid = start + (ends - start) 2;
if (arr[mid] == target) {
return mid;
}
if (arr[mid] > target) {
return binarySearch(arr, start, mid - 1, target);
}
return binarySearch(arr, mid + 1, ends, target);
}
return -1;
}
int main() {
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int target = 10;
int result = binarySearch(arr, 0, n - 1, target);
if (result == -1) {
cout << "Element is not present in array" << endl;
}
else {
cout << "Element is present at index " << result << endl;
}
return 0;
}
```
阅读全文