写一段c语言代码,实现线性表的顺序查找和二分查找 ,假定本次实验中要查找的记录只有一个数据项,且该数据项为整数,用数组来存储记录集合。 说明2:数据集可以手动输入,也可以随机生成
时间: 2024-02-22 17:00:11 浏览: 74
顺序查找:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
int linear_search(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
int main(void) {
int arr[MAX_SIZE];
int n, key;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the key to search: ");
scanf("%d", &key);
int index = linear_search(arr, n, key);
if (index == -1) {
printf("Not found\n");
} else {
printf("Found at index %d\n", index);
}
return 0;
}
```
二分查找:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_SIZE 100
int binary_search(int arr[], int n, int key) {
int left = 0;
int right = n - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main(void) {
int arr[MAX_SIZE];
int n, key;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the key to search: ");
scanf("%d", &key);
int index = binary_search(arr, n, key);
if (index == -1) {
printf("Not found\n");
} else {
printf("Found at index %d\n", index);
}
return 0;
}
```
注意:上述代码中的数组是有序的。可以手动输入数据集,也可以随机生成。
阅读全文