c - 线性搜索代码显示我的项目不存在。请帮我更正

标签 c algorithm linear-search

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/

相关文章:

java - Leetcode 110. Balanced Binary Tree 请问我的解为什么错了?

java - 线性和二分搜索逻辑错误

c - 为什么for循环没有被执行?(线性搜索)

c - 需要你的帮助来找到我的回文

c - 如何区分二进制负数?

c - 反序列化函数(字节数组到 uint32)

c# - 用其他子数组替换所有子数组的高效算法

c++ - 数组中的最大 X 值

algorithm - 我们能否找到元素是否存在于数组 {1,2,...,n} 中,其中元素为 Θ(m) 中的 m 个不同元素?

c - 使用移位运算符拆分大十进制数