1.c语言编写程序实现顺序查找和折半查找。
时间: 2024-05-16 22:17:00 浏览: 13
顺序查找:
```c
#include <stdio.h>
int seqSearch(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, 5, 8, 12, 16, 23, 38, 56, 72, 91 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 23;
int index = seqSearch(arr, n, x);
if (index == -1) {
printf("Element not found\n");
}
else {
printf("Element found at index %d\n", index);
}
return 0;
}
```
折半查找:
```c
#include <stdio.h>
int binarySearch(int arr[], int l, int r, int x) {
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == x) {
return mid;
}
else if (arr[mid] < x) {
l = mid + 1;
}
else {
r = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = { 2, 5, 8, 12, 16, 23, 38, 56, 72, 91 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 23;
int index = binarySearch(arr, 0, n - 1, x);
if (index == -1) {
printf("Element not found\n");
}
else {
printf("Element found at index %d\n", index);
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)