回复 2楼 yuccn
#include<stdio.h>
#include<stdlib.h>
#define N 5
typedef int KeyType;
typedef int ElemType;
struct SSTable
{
ElemType *elem;
int length;
};
void Creat_Seq(SSTable &ST,ElemType r[],int n)
{
int i;
ST.elem=(ElemType*) calloc (n+1,sizeof(ElemType));
if(!ST.elem)
exit(0);
for(i=1;i<=n;i++)
ST.elem[i]=r[i-1];
ST.length=n;
}
int Search_Seq(SSTable ST,KeyType key)
{
int i=ST.length;
ST.elem[0]=key;
while(ST.elem[i]!=key)
--i;
return i;
}
int Search_Bin(SSTable ST,KeyType key)
{
int low,high,mid,i;
int find=0;
low=1; high=ST.length;
if(mid%2==0)
mid=(low+high)/2;
if(mid%2==1)
mid=(low+high+1)/2;
while (low<=high&&find==0)
{
if(mid%2==0)
mid=((low+high)/2);
if(mid%2==1)
mid=(low+high+1)/2;
if(key<ST.elem[mid] )
high=mid-1;
else if (key>ST.elem[mid])
low=mid+1;
else
{
i=mid;
find=1;
}
}
if(find==1)
return i;
else
return 0;
}
void Traverse(SSTable ST)
{
int i;
for(i=1;i<=ST.length;i++)
printf("%d
",ST.elem[i]);
return;
}
void main()
{
ElemType r[N]={324,315,128,387,356};
SSTable st;
int i,j;
long s;
Creat_Seq(st,r,N);
//
由数组r产生顺序表静态查找表st
Traverse(st);
//按顺序输出st
printf("\n请输入查找的关键字:");
scanf_s("%d",&s);
printf("1:顺序查找法,
2:折半查找
");
scanf_s("%d",&j);
{
if(j==1)
i=Search_Seq(st,s);
if(j==2)
i=Search_Bin(st,s);
}
if(i)
printf("要查找的关键字的序号为%d\n",i);
else
printf("没找到\n");
return;
}