查找表的算法

发布时间:2024年01月04日

typedef int ElemType;
typedef struct {
?? ?ElemType *elem;
?? ?int length;
}SSTable;

typedef int KeyType;


//建立查找表
void create(SSTable &ST)
{
?? ?ST.elem=(ElemType*)malloc(11*sizeof(ElemType));
?? ?ST.length=0;
?? ?for(int i=1;i<=10;i++)
? ? {
? ? ? ? printf("请输入第%d个元素值:",i);
? ? ? ? scanf("%d",&ST.elem[i]);
? ? ? ? ST.length++;
? ? ? ? printf("\n");
? ? }
}
//二分查找
int search_Bin(SSTable ST, KeyType key )
{
?? ?int low=1,high=ST.length;
?? ?int mid;
?? ?while(low<=high)
? ? {
? ? ? ? mid=(low+high)/2;
? ? ? ? if(key == ST.elem[mid])
? ? ? ? ? ? return mid;
? ? ? ? else if(key > ST.elem[mid])
? ? ? ? ? ? low=mid+1;
? ? ? ? else
? ? ? ? ? ? high=mid-1;
? ? }
? ? return 0;
}

main()
{
? ? SSTable ST;
? ? create(ST);
? ? printf("查找关键字21的结果为:%d\n", search_Bin(ST, 21));
? ? free(ST.elem);
? ? return 0;
}
?

文章来源:https://blog.csdn.net/yst12138/article/details/135262824
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。