#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
typedef struct
{
char name;
int key;
}ElemType;
typedef struct
{
ElemType *R;
int length;
}SSTable;
int Init(SSTable *ST)
{
(*ST).R=(ElemType *)malloc(sizeof(ElemType)*MAXSIZE);
(*ST).length=0;
return 0;
}
int Creat(SSTable *ST,int n)
{
printf("请按照由小到大的顺序输入%d组数据,将建立顺序表!",n);
int x;char c;
for(int i=1;i<n+1;i++)
{
scanf("%c",&c);
scanf("%d",&x);
(*ST).R[i].name=c;
(*ST).R[i].key=x;
(*ST).length++;
}
return 0;
}
int Search_Bin(SSTable ST,int key)
{
int low=1,high=ST.length,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()
{
int x;
SSTable ST;
Init(&ST);
Creat(&ST,5);
printf("请输入你要查找的数:");
scanf("%d",&x);
printf("%d在第%d组数据中\n",x,Search_Bin(ST,x));
printf("第%d组数据是 %c%d",Search_Bin(ST,x),ST.R[Search_Bin(ST,x)].name,ST.R[Search_Bin(ST,x)].key);
return 0;
}
【数据结构C语言】顺序表的查找——折半查找
最新推荐文章于 2023-06-09 19:02:00 发布