#include<stdio.h>#include<stdlib.h>#define MAXSIZE 50intnum1=0;
intnum2=0;
typedefstruct{
intelem[MAXSIZE];
intlength;
}sqlist;
intsearch(sqlistST, intkey)
{
inti;
ST.elem[0] =key;
for (i=ST.length; ST.elem[i] !=key; --i)
{num1=num1+1;
}
printf("顺序查找次数为:%d\n", num1);
returni;
}
intsearch_bin(sqlistST, intkey)
{
intlow, high, mid;
low=1;
high=ST.length;
while (low<=high)
{
mid= (low+high) /2;
if (key==ST.elem[mid])
{num2=num2+1;
printf("折半查找次数为:%d\n", num2);
returnmid;}
elseif(key<ST.elem[mid]) {
num2=num2+1; high=mid-1;
}
else {
num2=num2+1; low=mid+1;
}
}
return0;
}
voidcreate_list(sqlist*ST)
{
inti;
printf("输入元素个数n\n");
scanf("%d", &ST->length);
for (i=1; i<=ST->length; i++)
{
printf("\n data %d=", i);
scanf("%d", &(ST->elem[i]));
}
}
intmain()
{
sqlistST;
intkey;
create_list(&ST);
printf("查找元素e=");
scanf("%d", &key);
if(search(ST, key) ==0)
{
printf("fail!\n");
}
else {
printf("success!\n");
printf("顺序查找位置为:%d\n", search(ST, key));
printf("折半查找位置为:%d\n", search_bin(ST, key));
}
return0;
}