实现两种基本算法,顺序查找和折半查找
typedef struct
{
KeyType key; //关键字域
}ElemType;
typedef struct
{
ElemType data[LIST_SIZE]; //查找表存储空间
int length; //表长度
}SSTable;
void CreateSearch(SSTable *ST) //创建查找表
void Output(SSTable *ST) //输出查找表
int Search_Seq(SSTable *ST,KeyType key)//顺序查找
int Binary_Search(SSTable *ST,KeyType key)//折半查找
#include
#define LIST_SIZE 50
#define KeyType int
typedef struct
{
KeyType key; //关键字域
}ElemType;
typedef struct
{
ElemType data[LIST_SIZE]; //查找表存储空间
int length; //表长度
}SSTable;
void CreateSearch(SSTable *ST)
{
int i;
printf("请输入元素个数:");
scanf("%d",&ST->length);
printf("输入由小到大的顺序,输入%d个元素.\n",ST->length);
for(i=1;i<=ST->length;i++)
{
printf("输入第%d个元素: ",i);
scanf("%d",&ST->data[i].key);
}
}
void Output(SSTable *ST)
{
for(int i=1;i<=ST->length;i++)
{
printf("%d\t",ST->data[i].key);
}
}
int Search_Seq(SSTable *ST,KeyType key)
{//在顺序表ST中查找关键字为key的数据元素,若找到返回该元素在数组中的下标,否则返回0
int i;
ST->data[0].key=key;
for(i=ST->length;ST->data[i].key!=key;i--);
return i;
}
int Binary_Search(SSTable *ST,KeyType key)
{//在顺序表ST中折半查找关键字为key的数据元素,若找到返回该元素在数组中的下标,否则,返回0
int low,high,mid;
int flag;
low=1;
high=ST->length;
flag=0;
while(low<=high){
mid=(low+high)/2;
if(keydata[mid].key)
high=mid-1;
else
if(key>ST->data[mid].key)
low=mid+1;
else{
flag=mid;
break;
}
}
return flag;
}
void main(void)
{
SSTable ST;
char ch='y';
int n;
int key;
int result;
while(ch=='y'||ch=='Y')
{
printf("\n\t\t 查找");
printf("\n\t\t 1.创建查找表");
printf("\n\t\t 2.显示查找表");
printf("\n\t\t 3.顺序查找");
printf("\n\t\t 4.折半查找");
printf("\n\t\t 0.退 出");
printf("\n\t\t请选择(0--3):");
scanf("%d",&n);
getchar();
switch(n)
{
case 1:CreateSearch(&ST);break;
case 2:Output(&ST);break;
case 3:printf("请输入需要查找的关键字:");
scanf("%d",&key);
result=Search_Seq(&ST,key);
if(result==0)
printf("没有找到关键字为:%d的数据。\n",key);
else
printf("关键字为%d的数据,在查找表的位置:%d。",key,result);
break;
case 4:printf("请输入需要查找的关键字:");
scanf("%d",&key);
result=Binary_Search(&ST,key);
if(result==0)
printf("没有找到关键字为:%d的数据。\n",key);
else
printf("关键字为%d的数据,在查找表的位置:%d。",key,result);
break;
case 0:ch='n';break;
default:printf("/n/t/t输出错误!请重新输入!");
}
printf("\n\n\n\n\n\n\n");
}
}