采用顺序存储结构创建静态查找表——有序表,对有序表进行二分查找,用C语言展示
时间: 2023-07-19 08:18:22 浏览: 50
好的,下面我来用C语言展示如何采用顺序存储结构创建有序表,并对有序表进行二分查找。
```c
#include <stdio.h>
typedef struct {
int key;
int value;
} Element;
#define MAX_SIZE 100
Element table[MAX_SIZE];
int count = 0;
int binarySearch(int key) {
int left = 0;
int right = count - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (table[mid].key == key) {
return table[mid].value;
} else if (table[mid].key < key) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
// 创建有序表
table[0].key = 1;
table[0].value = 100;
table[1].key = 3;
table[1].value = 200;
table[2].key = 5;
table[2].value = 300;
table[3].key = 7;
table[3].value = 400;
count = 4;
// 二分查找
int value = binarySearch(5);
printf("二分查找5的值为:%d\n", value);
return 0;
}
```
输出结果为:
```
二分查找5的值为:300
```
可以看到,二分查找能够正确地找到目标元素,并返回其对应的值。
相关推荐
![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)
![](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)