4. 函数bisearch 的作用是应用折半查找法从存有N个整数的升序数组a中对关键字key进行查找。请将程序补充完整。 #include<stdio.h> #define N 15 int bisearch(int a[N], int key) { int low=0, high=N-1, mid; while(______(1)_________) { mid=(low+high)/2; if(key<a[mid]) ______(2)________; else if(key>a[mid]) low=mid+1; else return mid; } return _____(3)________ ; } void main() { int b[N],n,i,j; printf("Please input a %d element increasing sequence: ", N); for(i=0;i<N;i++) { printf("b[%d]= ",i); scanf("%d",&b[i]); } printf("Please input a searching key: "); scanf("%d",&n); j=bisearch(b,n); if(j==1) printf("Don’t find %d\n",n); else printf("b[%d]=%d\n",j,n); }
时间: 2024-01-07 19:03:45 浏览: 78
下面是完整的程序,包括了需要填空的部分:
```c
#include <stdio.h>
#define N 15
int bisearch(int a[N], int key) {
int low = 0, high = N - 1, mid;
while (low <= high) {
mid = (low + high) / 2;
if (key < a[mid])
high = mid - 1;
else if (key > a[mid])
low = mid + 1;
else
return mid;
}
return -1;
}
int main() {
int b[N], n, i, j;
printf("Please input a %d element increasing sequence: ", N);
for (i = 0; i < N; i++) {
printf("b[%d]= ", i);
scanf("%d", &b[i]);
}
printf("Please input a searching key: ");
scanf("%d", &n);
j = bisearch(b, n);
if (j == -1)
printf("Don’t find %d\n", n);
else
printf("b[%d]=%d\n", j, n);
return 0;
}
```
需要填空的部分如下:
1. `while (low <= high)`
2. `high = mid - 1;`
3. `-1;`
这个程序实现了一个折半查找(二分查找)算法,用于在一个有序数组中查找指定元素的位置。算法的核心思想是将数组分成两半,然后判断目标元素在左半边还是右半边,进而逐步缩小查找范围,直到找到目标元素或者确定不存在目标元素。
阅读全文