在一个程序中实现查找表的顺序查找与折半查找
时间: 2024-05-07 18:22:47 浏览: 84
C语言实现顺序表的顺序查找和折半查找
下面是一个实现查找表的顺序查找与折半查找的示例程序:
```c
#include <stdio.h>
// 定义查找表
int table[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
// 顺序查找函数
int sequential_search(int key) {
int i;
for (i = 0; i < sizeof(table)/sizeof(int); i++) {
if (table[i] == key) {
return i;
}
}
return -1;
}
// 折半查找函数
int binary_search(int key) {
int left = 0, right = sizeof(table)/sizeof(int) - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (table[mid] == key) {
return mid;
} else if (table[mid] < key) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int key;
printf("Enter the key to search: ");
scanf("%d", &key);
int index = sequential_search(key);
if (index != -1) {
printf("Sequential search: Found at index %d.\n", index);
} else {
printf("Sequential search: Not found.\n");
}
index = binary_search(key);
if (index != -1) {
printf("Binary search: Found at index %d.\n", index);
} else {
printf("Binary search: Not found.\n");
}
return 0;
}
```
该程序定义了一个查找表 `table`,包含了一些整数。顺序查找函数 `sequential_search` 从头到尾遍历表中的每个元素,直到找到目标元素或遍历完整个表。折半查找函数 `binary_search` 利用查找表已经有序的特点,进行二分查找。程序首先输入要查找的关键字,然后依次调用两个查找函数,输出查找结果。
阅读全文