我正在尝试编写一个递归函数,用于在数组中进行线性搜索,它还会返回找到元素的第一个索引。
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;
}
}
但是,当我试图捕获main函数中返回的值时,当元素不存在于数组中时,返回size的值而不是-1。我不知道为什么会发生这种情况。
发布于 2020-07-08 13:47:01
尝尝这个。我在代码中添加了一些注释,这样您就可以更好地理解它。
/* i is the initial position. When you are making a call to linearSearch it should be set to 0 */
int linearSearch(int *A, int size, int val, int i)
{
/* When you reach end of the array and havent found value, then return -1 */
/* Every recursive function should have an exit condition */
if(i == size)
return -1;
/* when we found a value return the index */
if (A[i] == val)
return i;
else
/* If not then move to the next value in the array by incrementing index and recurse */
return linearSearch(A, size, val, i + 1);
}
https://stackoverflow.com/questions/59832129
复制相似问题