设计一个函数模板find,用于对一个有序数组采用二分法查找指定数据的元素下标。用int,char型数据进行测试。
时间: 2024-03-05 17:51:57 浏览: 32
好的,以下是一个实现二分查找的函数模板find:
```c++
template <typename T>
int find(T arr[], int n, T target) {
int l = 0, r = n - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] > target)
r = mid - 1;
else
l = mid + 1;
}
return -1; // 找不到返回-1
}
```
可以看到,这个函数采用了经典的二分查找算法,其中T是模板参数,表示数组中元素的类型,n表示数组的长度,target表示要查找的目标元素。
下面是一个示例程序,用于测试上述函数模板:
```c++
#include <iostream>
using namespace std;
template <typename T>
int find(T arr[], int n, T target) {
int l = 0, r = n - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] > target)
r = mid - 1;
else
l = mid + 1;
}
return -1; // 找不到返回-1
}
int main() {
int arr1[] = {1, 3, 5, 7, 9};
int idx1 = find(arr1, 5, 5);
cout << "idx1 = " << idx1 << endl; // 输出:idx1 = 2
char arr2[] = {'a', 'b', 'c', 'd', 'e'};
int idx2 = find(arr2, 5, 'd');
cout << "idx2 = " << idx2 << endl; // 输出:idx2 = 3
return 0;
}
```
可以看到,我们先定义了两个数组,一个是int类型的,一个是char类型的,然后分别调用了find函数来查找数组中的元素,并输出了查找结果。
希望我的回答能够帮到你,如果还有其他问题,可以继续问我哦!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)