typedef char KeyType;
typedef int OthenrType;
typedef struct{
KeyType Key;
OthenrType othenr_data;
}RecordType;
typedef struct{
RecordType L[LIST_SLZE+1];
int length;
}Recordlist;
void createlist(Recordlist *l)
{
int i,b;
int len;
OthenrType j;
printf("输入线型表长度:");
scanf("%d",&len);
l->length=len;
for(i=1;i<=len;i++)
{
printf("输入线型表第%d个整数元素:",i);
fflush(stdin);
scanf("%d",&j);
l->L[i].Key=j;
}
for(i=1;i<=len;i++)
{
for(j=i;j<=len;j++)
{
if ( l->L[i].Key > l->L[j].Key)
{
b=l->L[i].Key;
l->L[i].Key=l->L[j].Key;
l->L[j].Key=b;
}
}
}
}
int czlist(Recordlist l,OthenrType k)
{
OthenrType high,low,mid;
high=l.length;
low=1;
while (low<=high)
{
mid=(low+high)/2;
if (kl.L [mid].Key ) return mid;
if(k>l.L [mid].Key)
low=++mid;
else
high=--mid;
}
return (0);
}
int main()
{
Recordlist l;
OthenrType k;
int list;
createlist(&l);
int i;
for (i=1;i<=l.length;i++)
printf("% d",l.L[i].Key );
printf("\n");
printf("输入要查找的整数元素:");
fflush(stdin);
scanf("%d",&k);
list=czlist(l,k);
if (list0)
printf("没有找到该元素,返回值为:%d\n",list);
else
printf("找到了该元素,返回值为:%d\n",list);
return 0;
}
这次实验主要掌握折半查找算法的原理,那么剩下的就是编写代码和调试程序。通过这次实验,通过这次实验,让我体会到同样的数据在不同的查询方法下有着不同的查询效率。对折半查找算法有了更加深刻的了解,同时在一定程度上提高了编程能力。
原文:https://www.cnblogs.com/lhjy/p/13057768.html