C语言从键盘输入一整数,然后在一个整型一维数组 a[20]中,用折半查找法找出该数是数 组中第几个元素的值。如果该数不在数组中,则打印”No found”。
时间: 2024-05-08 09:16:47 浏览: 75
```c
#include <stdio.h>
int binary_search(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int a[20];
int n, target;
printf("请输入数组长度(不超过20): ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("请输入第%d个数: ", i + 1);
scanf("%d", &a[i]);
}
printf("请输入要查找的数: ");
scanf("%d", &target);
int index = binary_search(a, n, target);
if (index == -1) {
printf("No found\n");
} else {
printf("%d 是数组中第 %d 个元素\n", target, index + 1);
}
return 0;
}
```
阅读全文