[英]Linear Search Code Shows that my item is not present.Please help me make corrections
This is the function for linear search where i am only taking one variable x that is the to search for item variable
这是线性搜索的功能,其中我仅采用一个变量x来搜索项目变量
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
存在76,因此它应该显示其索引位置,但对于两个都显示-1,这意味着在第二个测试用例中都不存在
b=lsrch(99);
printf("%d",a);
printf("%d",b);
}
Logical Error in your code - the foloowing part of your code was incorrect - 您代码中的逻辑错误-您代码中的以下部分不正确-
if(x==arr[i])
{
return i
}
else
return -1
At the first pass itself if condition evaluates false and -1 is returned. 在第一遍本身,如果条件评估为假,则返回-1。
Correct Code - 正确的代码-
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;
}
}
return -1;
}
int main()
{
int a,b;
a=lsrch(76);
return 0;
}
The problem is that you're breaking out of the loop too early. 问题是您太早脱离循环了。
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
}
}
As written, as soon as your code finds a number that doesn't match x
, it will return -1. 如所写,一旦您的代码找到与
x
不匹配的数字,它将返回-1。 It will never proceed to check the rest of the numbers in arr
. 它将永远不会检查
arr
的其余数字。
If you compile with gcc -Wall -Werror
, the compiler will point out that you've made a mistake: 如果使用
gcc -Wall -Werror
进行编译,则编译器将指出您犯了一个错误:
linsearch.c: In function ‘lsrch’:
linsearch.c:17:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
This means that you're not returning anything in the case that the loop finishes - causing undefined behavior. 这意味着在循环结束的情况下,您不会返回任何信息,这会导致未定义的行为。
The solution is to postpone the return -1
until after the loop has exhausted all of the values in arr
. 解决的办法是推迟
return -1
直到循环已经用尽了所有的值后 arr
。
Also, your loop terminates when i == 5
but you've not checked the last number in arr
. 同样,当
i == 5
时循环终止,但您尚未检查arr
的最后一个数字。 Let's use a macro to avoid having to hard-code this value. 让我们使用宏来避免必须对该值进行硬编码。
#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
}
int lsrh(int x){
int i,a[6]={2,4,5,76,2,1};
for(i=0;i<6;i++){
if(a[i]==x)
return i;
}
return -1;
}
use this it will work 使用它会起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.