用C++实现完整代码编程分别对有序顺序表的顺序查找,二分查找算法进行实现。 测试用例:{10,20,30,40,50,60,70,80,90},查找元素为90和35
时间: 2024-03-09 16:48:17 浏览: 15
好的,以下是用C++实现有序顺序表的顺序查找和二分查找的完整代码:
```cpp
#include <iostream>
using namespace std;
// 定义有序顺序表结构体
struct SeqList {
int *data;
int length;
};
// 初始化顺序表
void InitList(SeqList &L, int len) {
L.data = new int[len];
L.length = len;
for (int i = 0; i < len; i++) {
L.data[i] = (i + 1) * 10;
}
}
// 顺序查找
int SeqSearch(SeqList L, int key) {
for (int i = 0; i < L.length; i++) {
if (L.data[i] == key) {
return i;
}
}
return -1;
}
// 二分查找
int BinarySearch(SeqList L, int key) {
int left = 0, right = L.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (L.data[mid] == key) {
return mid;
} else if (L.data[mid] > key) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
int main() {
SeqList L;
int len = 9;
InitList(L, len);
int key1 = 90;
int pos1 = SeqSearch(L, key1);
cout << "顺序查找 " << key1 << " 的位置为:" << pos1 << endl;
int key2 = 35;
int pos2 = SeqSearch(L, key2);
cout << "顺序查找 " << key2 << " 的位置为:" << pos2 << endl;
int key3 = 90;
int pos3 = BinarySearch(L, key3);
cout << "二分查找 " << key3 << " 的位置为:" << pos3 << endl;
int key4 = 35;
int pos4 = BinarySearch(L, key4);
cout << "二分查找 " << key4 << " 的位置为:" << pos4 << endl;
return 0;
}
```
运行结果如下:
```
顺序查找 90 的位置为:8
顺序查找 35 的位置为:-1
二分查找 90 的位置为:8
二分查找 35 的位置为:-1
```
可以看到,顺序查找找到了元素90的位置,但没有找到元素35的位置;而二分查找同时找到了元素90和35的位置,这是因为顺序表是有序的,二分查找利用了有序这一特点,可以快速定位元素位置。
相关推荐
![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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)