This is the function for linear search where i am only taking one variable x that is the to search for item variable
int lsrch(int x)
{int i;
int arr[6] = {2,4,5,76,2,1};
for(i=0;i<5;i++)
{
if(x==arr[i])
{
return i;
}
else
return -1;
}
}
int main()
{
int a,b;
a=lsrch(76);
76 is present so it should show its index location but it shows -1 for both meaning both are not present true for 2nd test case
b=lsrch(99);
printf("%d",a);
printf("%d",b);
}
最佳答案
问题是你太早地脱离了循环。
int lsrch(int x)
{
int i;
int arr[6] = {2,4,5,76,2,1};
for(i=0;i<5;i++)
{
if(x==arr[i])
{
return i;
}
else
return -1; // Incorrect
}
}
如前所述,一旦您的代码找到与 x
不匹配的数字,它将返回 -1。它永远不会继续检查 arr
中的其余数字。
如果您使用gcc -Wall -Werror
进行编译,编译器会指出您犯了一个错误:
linsearch.c: In function ‘lsrch’:
linsearch.c:17:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
这意味着在循环完成的情况下您不会返回任何内容 - 导致未定义的行为。
<小时/>解决方案是推迟返回 -1
,直到循环耗尽 arr
中的所有值之后。
此外,当 i == 5
时循环终止,但您尚未检查 arr
中的最后一个数字。让我们使用宏来避免硬编码该值。
#define ARRAY_LEN(x) (sizeof(x) / sizeof(x[0]))
int lsrch(int x)
{
int i;
int arr[] = {2,4,5,76,2,1};
for(i=0; i<ARRAY_LEN(arr); i++)
{
if(x==arr[i])
{
return i;
}
}
return -1; // Nothing left to check
}
关于c - 线性搜索代码显示我的项目不存在。请帮我更正,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41937379/