Algorithm 递归线性搜索

Algorithm 递归线性搜索,algorithm,recursion,return,linear-search,Algorithm,Recursion,Return,Linear Search,下面显示的代码工作正常。它打印在if子句中找到的元素的位置并退出。每当找不到元素时,该函数将运行到max,并向调用函数返回0,以指示未找到任何元素 但是,我正在考虑将找到的元素的位置返回给调用函数,而不是打印它。因为返回位置只会返回函数的早期实例,而不会返回调用函数,所以我很震惊。如何做到这一点 #include <stdio.h> #include <stdlib.h> int RLinearSearch(int A[],int n,int key) { if

下面显示的代码工作正常。它打印在if子句中找到的元素的位置并退出。每当找不到元素时,该函数将运行到max,并向调用函数返回0,以指示未找到任何元素

但是,我正在考虑将找到的元素的位置返回给调用函数,而不是打印它。因为返回位置只会返回函数的早期实例,而不会返回调用函数,所以我很震惊。如何做到这一点

#include <stdio.h>
#include <stdlib.h>

int RLinearSearch(int A[],int n,int key)
{
    if(n<1)
        return 0;
    else
    {
        RLinearSearch(A,n-1,key);
        if(A[n-1]==key)
        {
            printf("found %d at %d",key,n);
            exit(0);
        }
    }
    return 0;
}

int main(void) 
{
    int A[5]={23,41,22,15,32};   // Array Of 5 Elements 
    int pos,n=5;

    pos=RLinearSearch(A,n,23);

    if(pos==0)
        printf("Not found");

    return 0;
}
#包括
#包括
整数搜索(整数A[],整数n,整数键)
{
如果(n)
因为返回位置只会返回函数的早期实例,而不会返回调用函数,所以我很震惊

您可以通过从递归调用本身返回递归调用的结果来解决此问题:

int RLinearSearch(int A[], int n, int key) {
    if(n<0) { // Base case - not found
        return -1;
    }
    if(A[n]==key) { // Base case - found
        return n;
    }
    // Recursive case
    return RLinearSearch(A, n-1, key);
}

从您的问题开始:线性搜索返回键所在位置的索引该函数有三个参数:数组、搜索n的起始索引和搜索键k

所以你有:

int RLinearSearch(int[] A, int n, int k) 
{    
    if (n=>A.length()) return (-1);//base case(k not found in A)
    else if (A[n]==k) return n; //found case
    else return RLinearSearch(A, n+1, key); //continue case(keep looking through array)
}
int main(void){
    int A[5]={23,41,22,15,32};   // Array Of 5 Elements 
    int pos,n=0;

    pos=RLinearSearch(A,n,23);
    if (pos == -1) printf("Not Found");
    return 0;
}

您还可以更改它,以便只返回n-1,并获得正确的索引。

您可以使用尾部递归:

int LSearch(int a[],int n,int key,int i)
 {
  if(n==0) return -1;
  if(a[0]==key) return i;
  LSearch(a+1,n-1,key,++i);
 }
调用时使用函数调用:

LSeacrh(a,n,key,0);

所以这基本上是从数组的右到左找到元素的第一个匹配项。一旦找到第一个匹配项,函数就不再进一步查找了?@geek_code这是正确的,因为函数只能返回一个项,所以会返回右边的第一个项。我感谢您的回答。谢谢。注意,在这个数组中使用的函数如果将键指定为第一个元素(预期结果为0),则answer将返回数组的长度@CSBigSur不是真的:当搜索的元素位于数组的初始位置()时,函数将正确返回零。
LSeacrh(a,n,key,0);
public static int recursiveLinearSearch(int[] data, int index, int key){
    
    if(index==data.length)
        return -1;
    if(data[index]==key)
        return index;
    
    return recursiveLinearSearch(data, index+1, key);
    
}