c语言完成顺序查找与折半查找代码实现
时间: 2024-01-30 12:03:43 浏览: 3
顺序查找代码实现:
```c
#include <stdio.h>
int seq_search(int arr[], int n, int x)
{
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
return i;
}
}
return -1;
}
int main()
{
int arr[] = {3, 5, 7, 9, 11, 13, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 9;
int idx = seq_search(arr, n, x);
if (idx != -1) {
printf("%d is at index %d\n", x, idx);
} else {
printf("%d is not found\n", x);
}
return 0;
}
```
折半查找代码实现:
```c
#include <stdio.h>
int binary_search(int arr[], int n, int x)
{
int l = 0;
int r = n - 1;
while (l <= r) {
int m = (l + r) / 2;
if (arr[m] == x) {
return m;
} else if (arr[m] < x) {
l = m + 1;
} else {
r = m - 1;
}
}
return -1;
}
int main()
{
int arr[] = {3, 5, 7, 9, 11, 13, 15};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 9;
int idx = binary_search(arr, n, x);
if (idx != -1) {
printf("%d is at index %d\n", x, idx);
} else {
printf("%d is not found\n", x);
}
return 0;
}
```
阅读全文