利用顺序表作为查找表,创建一查找表,编程实现二分法查找算法,并对其进行验证。
时间: 2023-12-23 11:03:26 浏览: 46
二分法查找,也称折半查找,是一种针对有序数组的查找算法。其基本思想是,将有序数组分成左右两个部分,取数组中间的元素与目标元素进行比较,根据比较结果确定目标元素在左半部分还是右半部分,然后递归地在相应的部分中进行查找,直到找到目标元素或者确定目标元素不存在为止。
以下是利用顺序表实现二分法查找的代码:
```C++
#include <iostream>
using namespace std;
const int MAX_SIZE = 100;
// 定义顺序表结构体
struct SqList {
int data[MAX_SIZE]; // 存储数据元素的数组
int length; // 顺序表的长度
};
// 初始化顺序表
void InitList(SqList &L) {
L.length = 0;
}
// 向顺序表中插入元素
void Insert(SqList &L, int x) {
if (L.length >= MAX_SIZE) {
cout << "顺序表已满,无法插入!" << endl;
return;
}
L.data[L.length++] = x;
}
// 二分法查找算法
int BinarySearch(SqList L, int x) {
int left = 0, right = L.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (L.data[mid] == x) {
return mid;
} else if (L.data[mid] < x) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // 没找到目标元素
}
int main() {
SqList L;
InitList(L);
Insert(L, 1);
Insert(L, 3);
Insert(L, 5);
Insert(L, 7);
Insert(L, 9);
int index = BinarySearch(L, 5);
if (index == -1) {
cout << "未找到目标元素!" << endl;
} else {
cout << "目标元素在顺序表中的下标为:" << index << endl;
}
return 0;
}
```
在上面的代码中,我们首先定义了一个顺序表结构体 `SqList`,包含一个 `data` 数组和一个 `length` 成员变量。然后,我们通过 `InitList` 函数初始化顺序表,通过 `Insert` 函数向顺序表中插入元素。
最重要的是 `BinarySearch` 函数,它实现了二分法查找算法,其中 `left` 和 `right` 分别表示数组的左右端点,`mid` 表示数组的中间位置,每次将目标元素与中间元素进行比较,根据比较结果更新 `left` 或 `right` 的值,最终找到目标元素或者确定目标元素不存在。
最后,在 `main` 函数中我们创建一个顺序表,并插入一些元素。然后我们调用 `BinarySearch` 函数进行查找,如果找到目标元素,就输出其在顺序表中的下标,否则输出未找到目标元素的信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)