#include
#include
using namespace std;
#define SPACE 100
//顺序查找表的定义
typedef int ElemType;
typedef struct {
ElemType *elem; //数据元素存储空间基址,0 号单元留空
int length; //表长度
}SSTable;
//创建查找表
void CreateTable(SSTable &ST) {
//根据用户输入的长度,创建查找表空间,即为 elem 数组分配空间
//利用循环,提示用户输入查找表数据,并存储在查找表内
//为查找表长度赋值
cout << "请输入查找表的长度";
cin >> ST.length;
ST.elem = new ElemType[SPACE];//动态分布一个数组空间
cout << "请输入数据";
for (int i=1; i< ST.length; i++)
{
cin >> ST.elem[i];
}
}
//输出查找表元素
void Traverse(SSTable ST)
{
for (int i=1; i < ST.length; i++)
cout << ST.elem[i] << " ";
cout << endl;
//利用循环依次输出查找表元素
}
//在顺序表 ST 中顺序查找等于 key 的数据元素。
//若找到,则返回该元素在表中的位置,否则返回 0
int Search_Seq(SSTable &ST, ElemType key) {
ST.elem[0] = key;//设立一个哨兵
int i = ST.length;
for ( i; ST.elem[0] != ST.elem[i]; i--);//不用比较2次,既比较是不是越界,又比较是不是要找的数
return i ;
}
//在有序表 ST 中折半查找等于 key 的数据元素。
//若找到,则返回该元素在表中的位置,否则返回 0
int Search_Bin(SSTable &ST, ElemType key) {
int low, high, mid;
low = 1;
high = ST.length;
mid = (low + high) / 2;
while (key != ST.elem[mid] && low <= high)
{
if (key < ST.elem[mid])
high = mid - 1;
else
low = mid + 1;
mid= (low + high) / 2;
}
if (low <= high)
return mid;
else
return 0;
}
int main(void)
{
SSTable ST;
int c = 0;
ElemType key;
while (c != 3) {
cout << endl << "1. 顺序查找法";
cout << endl << "2. 折半查找法";
cout << endl << "3. 退出";
cout << endl << "选择功能(1~3):";
cin >> c;
switch (c)
{
case 1:
CreateTable(ST);
Traverse(ST);
cout << "请输入要查找的数据:";
cin >> key;
cout<> key;
cout<