主题:[讨论]超级简单题目 有些小问题
折半查找:
设有8个关键字序列k={ a1 , a2, a3 , a4 , a5 , a6 , a7 , a8 },使用数组作为存储方式,用折半查找法在序列中查找key= a2和key=b的数据元素(b不存在于k中),如果查找成功,则返回该元素的位置,如果查找不成功,则返回失败。
#define N 20
#include <stdio.h>
struct list
{int a[N];
int length;
}*l;
int search_bin(struct list *l)
{int low=1,high=l->length,mid,m;
printf("please input the elem you want search:\n");
scanf("%d",&m);
while(low<=high)
{
mid=(low+high)/2;
if(m==l->a[mid]) return mid;
else
{if(m<l->a[mid]) high=mid-1;
else low=mid+1;}
}
return 0;
}
void create_2(struct list *l,int n)
{int i;
l=(struct list*)malloc(sizeof(struct list));
printf("please input ten sorted elem(value from low to high):\n");
for(i=1;i<=n;i++)
scanf("%4d",&l->a[i]);
}
void print_2(struct list *l)
{int i;
printf("the elem of the list are:\n");
for(i=1;i<=l->length;i++)
printf("%4d",l->a[i]);}
main()
{struct list *l;
int x;
l=(struct list*)malloc(sizeof(struct list));
l->length=8;
create_2(l,l->length);
print_2(l);
x=search_bin(l);
if(x!=0)printf("The position of this elem is %d\n",x);
else printf("Can't find this elem in this list!\n");
}运行时有问题,不知道错在哪儿?
设有8个关键字序列k={ a1 , a2, a3 , a4 , a5 , a6 , a7 , a8 },使用数组作为存储方式,用折半查找法在序列中查找key= a2和key=b的数据元素(b不存在于k中),如果查找成功,则返回该元素的位置,如果查找不成功,则返回失败。
#define N 20
#include <stdio.h>
struct list
{int a[N];
int length;
}*l;
int search_bin(struct list *l)
{int low=1,high=l->length,mid,m;
printf("please input the elem you want search:\n");
scanf("%d",&m);
while(low<=high)
{
mid=(low+high)/2;
if(m==l->a[mid]) return mid;
else
{if(m<l->a[mid]) high=mid-1;
else low=mid+1;}
}
return 0;
}
void create_2(struct list *l,int n)
{int i;
l=(struct list*)malloc(sizeof(struct list));
printf("please input ten sorted elem(value from low to high):\n");
for(i=1;i<=n;i++)
scanf("%4d",&l->a[i]);
}
void print_2(struct list *l)
{int i;
printf("the elem of the list are:\n");
for(i=1;i<=l->length;i++)
printf("%4d",l->a[i]);}
main()
{struct list *l;
int x;
l=(struct list*)malloc(sizeof(struct list));
l->length=8;
create_2(l,l->length);
print_2(l);
x=search_bin(l);
if(x!=0)printf("The position of this elem is %d\n",x);
else printf("Can't find this elem in this list!\n");
}运行时有问题,不知道错在哪儿?