折半查找

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值