建立一个有序的顺序表,利用折半查找方法查找元素。要求能进行多次查找,并对每次查找输出结果,成功则输出在有序表中的位置,失败则输出“无此元素”。使之在vs2022运行
时间: 2024-03-18 19:41:12 浏览: 23
好的,以下是实现代码:
```c++
#include<iostream>
using namespace std;
// 有序顺序表定义
const int MAXSIZE = 100;
struct SeqList {
int data[MAXSIZE];
int length;
};
// 折半查找
int binarySearch(SeqList L, int x) {
int low = 0, high = L.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (L.data[mid] == x) {
return mid;
}
else if (L.data[mid] > x) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
return -1;
}
int main() {
SeqList L;
int n;
cout << "请输入有序顺序表的长度:";
cin >> n;
cout << "请输入有序顺序表的元素:";
for (int i = 0; i < n; i++) {
cin >> L.data[i];
}
L.length = n;
int m;
cout << "请输入要查找的元素个数:";
cin >> m;
cout << "请输入要查找的元素:" << endl;
for (int i = 0; i < m; i++) {
int x;
cin >> x;
int res = binarySearch(L, x);
if (res == -1) {
cout << "无此元素" << endl;
}
else {
cout << "元素" << x << "在有序表中的位置为:" << res << endl;
}
}
return 0;
}
```
在这个程序中,我们首先定义了一个有序的顺序表结构体,包含了一个数组和一个表示长度的变量。然后我们通过输入来初始化这个有序顺序表,并使用折半查找来查找元素。最后,我们可以进行多次查找,并对每次查找输出结果。
希望能够帮到你!
相关推荐
![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_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)
![](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)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)