1.建立顺序查找表,并在此查找表上实现顺序查找操作。 2.建立有序顺序查找表,并在此查找表上实现二分查找操作。c语言
时间: 2023-10-01 13:09:58 浏览: 70
1. 顺序查找表的实现:
```c
#include <stdio.h>
#define MAXSIZE 100
typedef struct {
int key;
char data;
} Element;
typedef struct {
Element elem[MAXSIZE];
int length;
} SeqList;
int SeqSearch(SeqList *L, int key) {
int i;
for (i = 0; i < L->length; i++) {
if (L->elem[i].key == key) {
return i;
}
}
return -1;
}
int main() {
SeqList L = {
{{1,'a'},{3,'b'},{5,'c'},{7,'d'},{9,'e'}}, 5
};
int i, key, pos;
printf("请输入查找的关键字:");
scanf("%d", &key);
pos = SeqSearch(&L, key);
if (pos == -1) {
printf("未找到关键字为%d的数据\n", key);
} else {
printf("关键字为%d的数据在顺序表中的位置为:%d\n", key, pos);
}
return 0;
}
```
2. 有序顺序查找表的实现:
```c
#include <stdio.h>
#define MAXSIZE 100
typedef struct {
int key;
char data;
} Element;
typedef struct {
Element elem[MAXSIZE];
int length;
} SeqList;
int BinarySearch(SeqList *L, int key) {
int low = 0, high = L->length - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (L->elem[mid].key == key) {
return mid;
} else if (L->elem[mid].key > key) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
int main() {
SeqList L = {
{{1,'a'},{3,'b'},{5,'c'},{7,'d'},{9,'e'}}, 5
};
int i, key, pos;
printf("请输入查找的关键字:");
scanf("%d", &key);
pos = BinarySearch(&L, key);
if (pos == -1) {
printf("未找到关键字为%d的数据\n", key);
} else {
printf("关键字为%d的数据在顺序表中的位置为:%d\n", key, pos);
}
return 0;
}
```
阅读全文