编写具体函数实现查找表的顺序查找与折半查找等基本操作,用c语言实现
时间: 2024-05-09 22:15:56 浏览: 104
以下是顺序查找和折半查找的基本操作实现,用C语言编写。
```c
#include <stdio.h>
// 顺序查找函数
int sequential_search(int arr[], int n, int key) {
int i;
for (i = 0; i < n; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
// 折半查找函数
int binary_search(int arr[], int n, int key) {
int left = 0;
int right = n - 1;
int 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 arr[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int n = sizeof(arr) / sizeof(int);
int key = 10;
int index;
// 顺序查找
index = sequential_search(arr, n, key);
if (index != -1) {
printf("顺序查找:找到了,下标是%d\n", index);
} else {
printf("顺序查找:没找到\n");
}
// 折半查找
index = binary_search(arr, n, key);
if (index != -1) {
printf("折半查找:找到了,下标是%d\n", index);
} else {
printf("折半查找:没找到\n");
}
return 0;
}
```
阅读全文