用C语言编写程序实现顺序查找和折半查找
时间: 2024-05-07 13:21:57 浏览: 103
以下是C语言实现顺序查找和折半查找的示例代码:
### 顺序查找
```c
#include <stdio.h>
int seq_search(int arr[], int n, int x) {
int i;
for (i = 0; i < n; i++) {
if (arr[i] == x) {
return i;
}
}
return -1;
}
int main() {
int arr[] = {2, 4, 7, 8, 10, 12};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 8;
int index = seq_search(arr, n, x);
if (index == -1) {
printf("%d not found", x);
} else {
printf("%d found at index %d", x, index);
}
return 0;
}
```
### 折半查找
```c
#include <stdio.h>
int binary_search(int arr[], int low, int high, int x) {
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] < x) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {2, 4, 7, 8, 10, 12};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 8;
int index = binary_search(arr, 0, n-1, x);
if (index == -1) {
printf("%d not found", x);
} else {
printf("%d found at index %d", x, index);
}
return 0;
}
```
阅读全文