编写一个c语言程序,内容是“给定一个有序序列,使用二分查找指定的值。(递归/非递归两种方法)
时间: 2024-03-03 18:50:11 浏览: 52
非递归方法:
```c
#include <stdio.h>
int binarySearch(int arr[], int n, int x) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == x) {
return mid;
}
if (arr[mid] < x) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {1, 3, 5, 7, 9, 11, 13};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 9;
int index = binarySearch(arr, n, x);
if (index == -1) {
printf("没有找到 %d\n", x);
} else {
printf("找到了 %d,位置是 %d\n", x, index);
}
return 0;
}
```
递归方法:
```c
#include <stdio.h>
int binarySearchRecursive(int arr[], int left, int right, int x) {
if (left > right) {
return -1;
}
int mid = left + (right - left) / 2;
if (arr[mid] == x) {
return mid;
}
if (arr[mid] < x) {
return binarySearchRecursive(arr, mid + 1, right, x);
} else {
return binarySearchRecursive(arr, left, mid - 1, x);
}
}
int binarySearch(int arr[], int n, int x) {
return binarySearchRecursive(arr, 0, n - 1, x);
}
int main() {
int arr[] = {1, 3, 5, 7, 9, 11, 13};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 9;
int index = binarySearch(arr, n, x);
if (index == -1) {
printf("没有找到 %d\n", x);
} else {
printf("找到了 %d,位置是 %d\n", x, index);
}
return 0;
}
```
阅读全文