#include<iostream>
#include<vector>
#include<string>
using namespace std;
template<class T>
class Search_Bin
{
public:
void Input_int(); //关键字录入
void Input_char(); //关键字录入
void Input_string(); //关键字录入
int Search(T key); //折半查找
void Output(int num); //输出
private:
vector<T> vec; //vec存储关键值key,vec[0]不用
int low,mid,high;
};
template<class T>
void Search_Bin<T>::Input_int()
{
T key;
cout<<"提示:令输入第一个字符为-1,从输入的第二个元素开始,作为关键字使用,以0作为结束标志"<<endl;
while(cin>>key&&key!=0)
{
vec.push_back(key);
}//while
cout<<endl;
}//Input_int
template<class T>
void Search_Bin<T>::Input_char()
{
T key;
cout<<"提示:令输入第一个字符为-1,从输入的第二个元素开始,作为关键字使用,以0作为结束标志"<<endl;
while(cin>>key&&key!='0')
{
vec.push_back(key);
}//while
cout<<endl;
}//Input_char
template<class T>
void Search_Bin<T>::Input_string()
{
T key;
cout<<"提示:令输入第一个字符为-1,从输入的第二个元素开始,作为关键字使用,以0作为结束标志"<<endl;
while(cin>>key&&key!="0")
{
vec.push_back(key);
}//while
cout<<endl;
}//Input_string
template<class T>
int Search_Bin<T>::Search(T key)
{
low=1;high=vec.size();
while(low<=high)
{
mid=(low+high)/2;
if(vec[mid]==key) return mid; //找到待查元素
else if(vec[mid]>key)
high=mid-1; //在前半区间查找
else
low=mid+1; //在后半区间查找
}//while
return 0;
}//Search
template<class T>
void Search_Bin<T>::Output(int num)
{
cout<<vec[num]<<endl;
}//Output
void main()
{
Search_Bin<int> S_Bin;
int key_Com;
cout<<"输入待查找的关键字key:";
cin>>key_Com;
S_Bin.Input_int();
S_Bin.Output(S_Bin.Search(key_Com));cout<<endl;
Search_Bin<char> S_Bin1;
char key_Com1;
cout<<"输入待查找的关键字key:";
cin>>key_Com1;
S_Bin1.Input_char();
S_Bin1.Output(S_Bin1.Search(key_Com1));cout<<endl;
Search_Bin<string> S_Bin2;
string key_Com2;
cout<<"输入待查找的关键字key:";
cin>>key_Com2;
S_Bin2.Input_string();
S_Bin2.Output(S_Bin2.Search(key_Com2));cout<<endl;
}//main
折半查找
最新推荐文章于 2024-09-03 10:11:41 发布