#include<stdio.h>
#define list_size 20
typedef int keytype;
typedef int othertype;
typedef struct
{
othertype key;
keytype other_data;
}recordtype;
typedef struct
{
recordtype r[list_size+1];
int length;
}recordlist;
//順序查找,設監視哨
int seqsearch(recordlist l,keytype k)
{
int i;
l.r[0].key=k;
i=l.length;
while(l.r[i].key!=k)
i--;
return i;
}
//順序查找,不設監視哨
int SeqSearch(recordlist l,keytype k)
{
int i;
i=l.length;
while(i>=1&&l.r[i].key!=k)
i--;
if(i>=1)
return i;
else
return 0;
}
//折半查找
int rinsrch(recordlist l,keytype k)
{
int mid;
int low=0;
int high=l.length;
while(low<=high)
{
mid=(low+high)/2;
if(k==l.r[mid].key)
return mid;
else if(k<l.r[mid].key)
high=mid-1;
else
low=mid+1;
}
return 0;
}
int main()
{
recordlist l;
int q,p,t,loc,len,i,length;
//創建
printf("請輸入表中元素個數:");
scanf("%d",&len);
length=len;
printf("輸入順序表的元素:");
for(i=0;i<=length;i++) //多了等號
{
scanf("%d",&l.r[i]);
}
//查找
printf("請輸入要查找的元素:");
scanf("%d",&loc);
q=seqsearch(l,loc);
if (p!= 0)
printf("元素下標1為:%d\n", q);
else
printf("該元素不存在!\n");
p=SeqSearch(l,loc);
if (p!= 0)
printf("元素下標2為:%d\n", q);
else
printf("該元素不存在!\n");
t=rinsrch(l,loc);
if (t!=0)
printf("元素下標3為:%d\n",t);
else
printf("該元素不存在!\n");
return 0;
}
哪兒錯了
uj5u.com熱心網友回復:
#include<stdio.h>
#define list_size 20
typedef int keytype;
typedef int othertype;
typedef struct
{
othertype key;
keytype other_data;
}recordtype;
typedef struct
{
recordtype r[list_size+1];
int length;
}recordlist;
//順序查找,設監視哨
int seqsearch(recordlist l,keytype k)
{
int i;
l.r[0].key=k;
i=l.length;
while(i > 0 && l.r[i].key!=k)
i--;
return i;
}
//順序查找,不設監視哨
int SeqSearch(recordlist l,keytype k)
{
int i;
i=l.length;
while(i>=1&&l.r[i].key!=k)
i--;
if(i>=1)
return i;
else
return 0;
}
//折半查找
int rinsrch(recordlist l,keytype k)
{
int mid;
int low=0;
int high=l.length;
while(low<=high)
{
mid=(low+high)/2;
if(k==l.r[mid].key)
return mid;
else if(k<l.r[mid].key)
high=mid-1;
else
low=mid+1;
}
return 0;
}
int main()
{
recordlist l;
int q,p,t,loc,len,i,length;
//創建
printf("請輸入表中元素個數:");
scanf("%d",&len);
if (len < list_size)
length=len;
else
length = list_size;
printf("輸入順序表的元素:");
for(i=1;i<=length;i++)
{
scanf("%d", &l.r[i].key);
}
l.length = length;
//查找
printf("請輸入要查找的元素:");
scanf("%d",&loc);
q=seqsearch(l,loc);
//if (p!= 0)
if (q != 0)
printf("元素下標1為:%d\n", q);
else
printf("該元素不存在!\n");
p=SeqSearch(l,loc);
if (p!= 0)
printf("元素下標2為:%d\n", q);
else
printf("該元素不存在!\n");
t=rinsrch(l,loc);
if (t!=0)
printf("元素下標3為:%d\n",t);
else
printf("該元素不存在!\n");
return 0;
}
供參考~
錯誤的地方不少,l的length沒有賦值,scanf對誰賦值?陣列越界訪問等等
建議對比代碼找一下自己的問題~
uj5u.com熱心網友回復:
l.length=length是什么意思啊轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/228185.html
標籤:C語言
上一篇:求助
下一篇:大佬,給點思路
