折半查找,完善以下程序:
#include
main()
{
int a[10]={1,3,5,7,9,11,13,15,17,19},k,low,high,mid,cnt;
low=0;high=9;cnt=0;
printf("请输入要查找的数:");
scanf("%d",&k);
while( 空1 )
{
cnt++;
mid=(low+high)/2;
if(k == a[mid])
break;
else if(k > a[mid])
空2
空3
}
#include
main()
{
int a[10]={1,3,5,7,9,11,13,15,17,19},k,low,high,mid,cnt;
low=0;high=9;cnt=0;
printf("请输入要查找的数:");
scanf("%d",&k);
while( 空1 )
{
cnt++;
mid=(low+high)/2;
if(k == a[mid])
break;
else if(k > a[mid])
空2
空3
}
举一反三
- 若输入52,则下面程序的运行结果是 。 main() {int a[8]={6,12,18,42,46,52,67,73}; int low=0,mid,high=7,x; printf("Input a x:"); scanf("%d",&x); while(low<=high) {mid=(low+high)/2; if(x>a[mid]) low=mid+1; else if(x Search Successful! The index is:5
- 若输入52<;CR>;,则下面程序的运行结果是。main(){int a[8]={6,12,18,42,46,52,67,73};int low=0,mid,high=7,x;printf("Input a x:");scanf("%d",&x);while(low<;=high){mid=(low+high)/2;if(x>;a[mid]) low=mid+1;else if(x<;a[mid]) high=mid-1;else break;}if(low<;=high) printf("Search Successful! The index is:%d\n",mid);else printf("Can't search!\n");}
- 代码填空【使用递归实现二分查找】 int binarySearch(int a[], int key, int low, int high) { if (low > high) return -1; int mid; mid = (low + high) / 2; if (key == a[mid]) return mid; else if (key < a[mid]) return ________(1)__________; else return ________(2)______________; }
- 折半查找法的思路是:先确定待查元素的范围,将其分成两半,然后测试位于中间点元素的值。如果该待查元素的值大于中间点元素,就缩小待查范围,只测试中点之后的元素;反之,测试中点之前的元素,测试方法同前。函数binary的作用是应用折半查找法从存有10个有序整数的a数组中对关键字m进行查找,若找到,返回其下标值;反之,返回 –1。请选择填空。 int binary(int a[10],int m) { int low=0,high=9,mid; while(low<=high) { mid= (low+high)/2; if(ma[mid]) ( ); else return(mid); } return( –1); } (1)A、high=mid – 1 B、low=mid+1 C、high=mid+1 D、low=mid–1 (2) A、high=mid–l B、low=mid+1 C、high=mid+l D、low=mid–1
- 写输出结果#include "stdio.h"int binary(int x, int a[], int n){ int low=0,high=n-l,mid; while(low<=high) { mid=(low+high)/2; if(x>a[mid]) high=mid-l; else if(x<a[mid]) low=mid+l; else return(mid); } void main(){ static int a[]={4,0,2,3,1}; int i,t,j; for(i=1;i<5;i++) t=a[i]; j=i-l; while(j>=0 && t>a[j]) { a[j+1]=a[j]; j--;} a[j+1]=t; } printf("%d\n",binary(3,a,5)); }