模板 二分法找数组.txt

来自「最后声明」· 文本 代码 · 共 58 行

TXT
58
字号
#include<iostream.h>
#define Max 100

template<class T>
class Sample
{
T A[Max];
int n;
public:
Binfind(){}
Binfind(T a[],int i);
int BinarySearch(T c);
void disp()
{
   for(int i=0;i<n;i++)
    cout<<A[i]<<" ";
   cout<<endl;
}
};

template<class T>
Binfind<T>::Binfind(T a[],int i)
{
n=i;
for(int j=0;j<i;j++)
   A[j]=a[j];
}

template<class T>
int Binfind<T>::BinarySearch(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;
}

void main()
{
char a[]="steffenmo";
Binfind<char> s(a,9);
cout<<"元素序列:";
s.disp();
cout<<"元素m的下标:"<<s.BinarySearch('m')<<endl;
int num[]={7,9,11,16,19,22};
Binfind<int> s1(num,6);
cout<<"元素序列:";
s1.disp();
cout<<"元素11的下标:"<<s1.BinarySearch(11)<<endl;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?