中值是在一组已排序数值的中间值。假如是奇数数列,则是中间的值,如果是偶数数列,则是中间两个数的平均值。 //求数组a中n个元素的中值[br][/br] double middle(const double a[],const int n) { int mid=(n-1)/2; if(n%2!=0) return a[mid]; else[br][/br] return【】; }
A: (a[mid]+a[mid+1])/2
B: (a[mid]+a[mid-1])/2
C: a[mid]/2
D: a[mid+1]/2
A: (a[mid]+a[mid+1])/2
B: (a[mid]+a[mid-1])/2
C: a[mid]/2
D: a[mid+1]/2
举一反三
- 代码填空【使用递归实现二分查找】 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)______________; }
- 若输入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");}
- 折半查找法的思路是:先确定待查元素的范围,将其分成两半,然后测试位于中间点元素的值。如果该待查元素的值大于中间点元素,就缩小待查范围,只测试中点之后的元素;反之,测试中点之前的元素,测试方法同前。函数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)); }
- 对于汉诺塔问题,假设盘子从上到下编号1,2,3,...,现在要把“start柱子上的n个盘子移到end柱子,mid柱子为辅助。如果用(a,b,c)表示将编号a的盘子从b柱子移到c柱子,那么下面哪个列表表示两个盘子的解决方法? A: [(1,start,mid),(1,mid,end),(2,start,end)] B: [(2,start,end),(1,mid,end),(1,start,mid)] C: [(1,start,end),(2,start,end),(1,mid,end)] D: [(1,start,mid),(2,start,end),(1,mid,end)]