采用顺序存储结构创建静态查找表,对查找表进行顺序查找和改进的顺序查找,用C语言展示
时间: 2024-02-25 21:52:56 浏览: 25
好的,下面我来用C语言展示如何采用顺序存储结构创建静态查找表,并对查找表进行顺序查找和改进的顺序查找。
```c
#include <stdio.h>
typedef struct {
int key;
int value;
} Element;
#define MAX_SIZE 100
Element table[MAX_SIZE];
int count = 0;
int sequentialSearch(int key) {
for (int i = 0; i < count; i++) {
if (table[i].key == key) {
return table[i].value;
}
}
return -1;
}
int improvedSequentialSearch(int key) {
int index = -1;
for (int i = 0; i < count; i++) {
if (table[i].key == key) {
index = i;
break;
}
}
if (index != -1 && index > 0) {
Element temp = table[index];
table[index] = table[index - 1];
table[index - 1] = temp;
}
return index == -1 ? -1 : table[0].value;
}
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 value1 = sequentialSearch(5);
printf("顺序查找5的值为:%d\n", value1);
// 改进的顺序查找
int value2 = improvedSequentialSearch(5);
printf("改进的顺序查找5的值为:%d\n", value2);
return 0;
}
```
输出结果为:
```
顺序查找5的值为:300
改进的顺序查找5的值为:300
```
可以看到,顺序查找和改进的顺序查找都能够正确地找到目标元素,并返回其对应的值。