1. 静态查找表技术 依据顺序查找算法和折半查找算法的特点,对下面的两个查找表选择一个合适的算法,设计出完整的C源程序。并完成问题: 查找表1 : { 8 ,15 ,19 ,26 ,33 ,41 ,47 ,52 ,64 ,90 } ,查找key = 41 查找表2 : {12 ,76 ,29 ,15 ,62 ,35 ,33 ,89 ,48 ,20 } ,查找key =35 查找key=41的算法: 比较次数: 查找key=35的算法: 比较次数: 顺序查找算法算法实现代码 折半查找算法算法实现代码
时间: 2024-03-22 20:39:36 浏览: 145
顺序查找算法实现代码:
```c
#include <stdio.h>
int sequential_search(int *arr, int len, int key) {
int i;
for (i = 0; i < len; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
int main() {
int arr1[] = {8, 15, 19, 26, 33, 41, 47, 52, 64, 90};
int arr2[] = {12, 76, 29, 15, 62, 35, 33, 89, 48, 20};
int len1 = sizeof(arr1) / sizeof(int);
int len2 = sizeof(arr2) / sizeof(int);
int key1 = 41;
int key2 = 35;
int pos1, pos2;
pos1 = sequential_search(arr1, len1, key1);
pos2 = sequential_search(arr2, len2, key2);
printf("查找key=41的算法比较次数:%d\n", pos1 + 1);
printf("查找key=35的算法比较次数:%d\n", pos2 + 1);
return 0;
}
```
折半查找算法实现代码:
```c
#include <stdio.h>
int binary_search(int *arr, int len, int key) {
int low = 0, high = len - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
int main() {
int arr1[] = {8, 15, 19, 26, 33, 41, 47, 52, 64, 90};
int arr2[] = {12, 76, 29, 15, 62, 35, 33, 89, 48, 20};
int len1 = sizeof(arr1) / sizeof(int);
int len2 = sizeof(arr2) / sizeof(int);
int key1 = 41;
int key2 = 35;
int pos1, pos2;
pos1 = binary_search(arr1, len1, key1);
pos2 = binary_search(arr2, len2, key2);
printf("查找key=41的算法比较次数:%d\n", pos1 + 1);
printf("查找key=35的算法比较次数:%d\n", pos2 + 1);
return 0;
}
```
阅读全文