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