代码填空【使用递归实现二分查找】 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)______________; }
举一反三
- 二分查找的递归实现,请选择正确的选项将函数补充完整。顺序表定义如下:typedef int datatype; /*假设数据类型为整型*/typedef struct { datatype data[100]; /*此处假设数据元素只包含一个整型的关键字域*/ int len; /*线性表长度*/ } slist; /*预定义的顺序表类型*/函数定义如下:int binsearch(slist L,datatype key,int low,int high){ int mid,k; if ( (1) ) return -1; /*检索不成功的出口条件*/ else { mid=(low+high)/2; /*二分*/ if ( (2) ) return mid; /*检索成功返回*/ if (L.data[mid]>key) return (3) ;/*递归地在前半部分检索*/ else return binsearch(L,key,mid+1,high); /*递归地在后半部分检索*/ }}
- 折半查找法的思路是:先确定待查元素的范围,将其分成两半,然后测试位于中间点元素的值。如果该待查元素的值大于中间点元素,就缩小待查范围,只测试中点之后的元素;反之,测试中点之前的元素,测试方法同前。函数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)); }
- 若输入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");}