4.试将折半查找的算法改写成递归算法。Itbisearch(sqlistL,itlow,ithigh,elemtypex){If(lowhigh)retur(0else{if(L.data[mid]==x)retur(mid);elseif(L.data[mid]x)bisearch(L,low,mid-1,x);elsebisearch(L,mid+1,high,x);}}//bisearch
举一反三
- 4.试将折半查找的算法改写成递归算法。Intbisearch(sqlistL,i...high,x);}}//bisearch
- 若输入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