#include"iostream"
#include"algorithm"
using namespace std;
class list{
private:
int data[20];
int length;
public:
list()
{
cout << "元素个数为:" << endl ;
cin >> length ;
cout << "请输入顺序表元素" << endl ;
for(int i=0;i<length;i++)
cin >> data[i];
}
void listsort()
{
sort(data,data+length);
for(int i=0;i<length;i++)
cout << data[i] << " ";
cout << endl ;
}
void binsearch(int key,int a)
{
int half;
half=a/2;
if(data[half]==key&&half!=0)
cout << "关键字的编号为: " << half+1 << endl ;
else if(data[half]>key&&key>data[0])
{
cout << "顺序表的中值比关键字大,继续在0—" << half << "中查找" << endl ;
binsearch(key,half);
}
else if(data[half]<key&&key<data[length-1])
{
cout << "顺序表的中值比关键字小,继续在" << half << "-" << length << "中查找" << endl ;
binsearch(key,half+length);
}
else
cout << "关键字不存在" << endl ;
}
int getlength()
{
return length;
}
};
void main()
{
int key;
list a;
a.listsort();
cout << "请输入关键字" << endl ;
cin >> key ;
a.binsearch(key,a.getlength());
}
设计一个程序,输出在顺序表中采用折半找法查找关键字的过程
最新推荐文章于 2023-11-29 19:35:53 发布