I am trying to write a recursive function for linear search in an array which also returns the first index at which the element is found.
int linearSearch(int *A, int size, int val)
{
if(size>0)
{
if(*A==val)
{
cout<<val<<" is found in the array!";
return i;
}
else
{
linearSearch(A+1,size-1,val);
i++;
}
}
else
{
cout<<val<<" is not there in the array!";
return -1;
}
}
However, when I am trying to catch the valued returned in the main function, value of size is returned instead of -1 in the case when the element is not present in the array. I am not able to figure out why is that happening.
Aucun commentaire:
Enregistrer un commentaire