c语言编写函数实现对n个数的进行顺序查找。(显示依次比较的数据以及比较次数,返回查找结果) 编写函数实现对n个数的进行二分查找。(显示依次比较的数据以及比较次数,返回查找结果)
时间: 2024-05-01 09:16:57 浏览: 11
顺序查找函数代码:
```
#include <stdio.h>
int sequential_search(int arr[], int n, int key) {
int i, count = 0;
for (i = 0; i < n; i++) {
count++;
printf("Comparing %d with %d\n", key, arr[i]);
if (arr[i] == key) {
printf("Total comparisons: %d\n", count);
return i; // 返回找到的下标
}
}
printf("Total comparisons: %d\n", count);
return -1; // 没有找到
}
int main() {
int arr[] = {5, 3, 8, 2, 9, 1, 7};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 9;
int index = sequential_search(arr, n, key);
if (index != -1) {
printf("%d is found at index %d\n", key, index);
} else {
printf("%d is not found\n", key);
}
return 0;
}
```
二分查找函数代码:
```
#include <stdio.h>
int binary_search(int arr[], int n, int key) {
int low = 0, high = n - 1, mid, count = 0;
while (low <= high) {
count++;
mid = (low + high) / 2;
printf("Comparing %d with %d\n", key, arr[mid]);
if (arr[mid] == key) {
printf("Total comparisons: %d\n", count);
return mid; // 返回找到的下标
} else if (arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
printf("Total comparisons: %d\n", count);
return -1; // 没有找到
}
int main() {
int arr[] = {1, 2, 3, 5, 7, 8, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 7;
int index = binary_search(arr, n, key);
if (index != -1) {
printf("%d is found at index %d\n", key, index);
} else {
printf("%d is not found\n", key);
}
return 0;
}
```