#include<stdio.h>
#include<stdlib.h>
typedef int KeyType;
typedef int InfoType;
typedef struct{
KeyType key;
InfoType otherinfo;
}ElemType;
typedef struct{
ElemType *R;
int Length;
}SSTable;
int search_Bin(SSTable ST,KeyType key){
int low=1;
int high=ST.Length;
int 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(){
//创建一个长度为10的顺序表
SSTable ST;
ST.R = (ElemType *)malloc(sizeof(ElemType) * 10);
ST.Length = 10;
//初始化数据
for(int i = 1; i <= ST.Length; ++i){
ST.R[i].key = i;
ST.R[i].otherinfo = i * 2;
}
for(int i=1;i<=10;i++){
printf("%d ",ST.R[i].key);
}
//查找元素
int key = 6;
int index = search_Bin(ST, key);
if(index > 0){
printf("元素 %d 的下标为 %d\n", key, index);
}
else{
printf("元素 %d 不存在\n", key);
}
free(ST.R); //释放内存
return 0;
}
6.2折半查找——结构体法
最新推荐文章于 2024-11-06 08:56:39 发布