#include <iostream>
using namespace std;
typedef struct{
int key;
}ElemType;
typedef struct{
ElemType *R;
int length;
}SSTable;
void Initial_table(SSTable &ST)
{
ST.R=new ElemType[100];
ST.length=0;
}
void Create_table(SSTable &ST)
{
int n;
cout<<"请输入需要创建的有序表的长度:"<<endl;
cin>>n;
cout<<"请依次输入顺序表中的元素,用空格隔开:"<<endl;
for(int i=1;i<=n;i++)
{
cin>>ST.R[i].key;
}
ST.length=n;
cout<<"创建完成!"<<endl;
}
int Search_table(SSTable ST,int key)
{
int low=1;
int high=ST.length;
int mid;
while (low<=high)
{
mid=(low+high)/2;
if(key==ST.R[mid].key)return mid;
else if(key<ST.R[mid].key)high=mid-1;
else low=mid+1;
}
return 0;
}
int main()
{
SSTable ST;
int i,num;
char c;
cout<<"欢迎使用折半查找:"<<endl;
Initial_table(ST);
Create_table(ST);
while(true)
{
cout<<"请输入需要查找的关键字:"<<endl;
cin>>num;
i=Search_table(ST,num);
if(i==0)cout<<"关键字不存在,查找失败!"<<endl;
else cout<<"查找成功!关键字的位置为:"<<i<<endl;
cout<<"是否继续查找?y:是,n:否"<<endl;
cin>>c;
if(c=='n')
{
cout<<"已退出!"<<endl;
break;
}
}
return 0;
}