编程实现如下功能: (1)根据输入的查找表的表长n和n个关键字值,建立顺序查找表,并在此查找表中用顺序查找方法查找给定关键值的记录,最后输出查找结果。 (2)根据输入的查找表的表长n和n个按升排列的关键字值,建立有序顺序查找表,并在此查找表中用二分查找方法查找给定关键值的记录,最后输出查找结果。 (3)主程序中要求设计一个菜单,允许用户通过菜单来多次选择执行哪一种查找操作。
时间: 2024-03-28 16:41:33 浏览: 19
好的,这个功能可以使用C语言实现。以下是代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义顺序查找函数
int sequentialSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
// 定义二分查找函数
int binarySearch(int arr[], int n, int key) {
int left = 0, right = n - 1, mid;
while (left <= right) {
mid = (left + right) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] > key) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
int main() {
int n, choice, key, index;
printf("请输入查找表的长度n:");
scanf("%d", &n);
int arr[n];
printf("请输入%d个关键字值:", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
while (1) {
printf("\n请选择查找方式:\n");
printf("1. 顺序查找\n");
printf("2. 二分查找\n");
printf("3. 退出程序\n");
printf("请输入选择的序号:");
scanf("%d", &choice);
if (choice == 1) {
printf("请输入要查找的关键字值:");
scanf("%d", &key);
index = sequentialSearch(arr, n, key);
if (index != -1) {
printf("查找成功!关键字值%d在查找表中的位置为%d。\n", key, index);
} else {
printf("查找失败!关键字值%d不在查找表中。\n", key);
}
} else if (choice == 2) {
printf("请输入要查找的关键字值:");
scanf("%d", &key);
index = binarySearch(arr, n, key);
if (index != -1) {
printf("查找成功!关键字值%d在有序查找表中的位置为%d。\n", key, index);
} else {
printf("查找失败!关键字值%d不在有序查找表中。\n", key);
}
} else if (choice == 3) {
printf("程序已退出。\n");
exit(0);
} else {
printf("输入错误!请重新输入。\n");
}
}
return 0;
}
```
在程序中,首先输入查找表的长度n和n个关键字值,并根据用户选择执行顺序查找或者二分查找。程序会反复执行,直到用户选择退出程序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)