第 3 题 【要求】设计一个模板类 BS,用于对一个有序数组采用二分法查找 元素下标。注:BS 是二分查找英文 Binary Search 的缩写。 【源代码】 #include<iostream> using namespace std; const int Max=100; template<class T> class BS { T A[Max]; int n; public: BS(){} BS(T a[], int i); int seek(T c); void disp() { for(int i=0; i<n; i++) cout<<A[i]<<" "; cout<<endl; } }; template<class T> BS<T>::BS(T a[],int i) { n=i; for(int j=0; j<i; j++) A[j]=a[j]; } template<class T> int BS<T>::seek(T c) { int low=0,high=n-1,mid; while(low<=high) { mid=(low+high)/2; if(A[mid]==c) return mid; else if (A[mid]<c) low=mid+1; else high=mid-1; } return -1; } int main() { char a[]="acegkmpwxz"; BS<char> s(a,10); cout<<"元素序列:"; s.disp(); cout<<"元素'g'的下标:"<<s.seek('g')<<endl; return 0; } |
|