Search code examples
clinear-search

Linear search is not returning the right index


My linear search is always returning -1 and I don't know why. I tried figuring it out but without success. The search function goes everytime to the "else" branch and the "then" is never executed.

#include <stdio.h>
#include <stdlib.h>
#define size 50000

int search(int n,int s,int v[s])
{
    int i;
    for(i=0;i<s;++i)
    {
        if(v[i]==n)
            return i;
        else
            return -1;
    }
}

int main(void)
{
    int valores[size];
    //start the vector and put values in it.
    for(int i=0;i<size;++i)
        valores[i]=(i+1)*2;
    //search the 50000 values
    for(int i=1;i<=size +1;++i)
    {
        int p=search(2*i,size,valores);
        if(p==-1)
            printf("Not found %d\n",i);
        else if(valores[p]!=2*i)
            printf("Found %d in wrong index: %d\n",i,p);
    }

    return 0;
}

Solution

  • You are always leaving your search function after the first index, 0;
    because at 0 it will either be identical and return i, or not and return -1.
    I assume that it does return 0, instead of -1, if you give n as v[0].
    Change that this way:

    for(i=0;i<s;++i)
    {
        if(v[i]==n)
            return i;
    }
    return -1;
    

    You get the warning you mention in a comment ("control reaches end of non-void function") because there is no return at the very end of your function. It would of course be unreachable, but the warning could have been a hint for finding the problem.