繁体   English   中英

在整数数组中查找整数元素:递归问题

[英]finding integer element in integer array:recursion issue

我编写了此递归方法以在整数数组中查找整数,但是它不起作用。 我尝试调试它,但不知道可能是什么问题。

这是代码

public static String inList(int[] primes,int a){
    int index = -9;
    if(primes.length>1){
        index = primes.length/2;
    }else{
        if(primes[0] == a){
            return "True";
        }else{
            return "False";
        }
    }
    if(primes[index] == a){
        return "True";
    }
    if(primes[index] > a){
        inList(Arrays.copyOfRange(primes, 0, index),a);
    }
    if(primes[index]<a){
        inList(Arrays.copyOfRange(primes, index, primes.length),a);
    }
            //shouldn't even get to this point, but eclipse insisted I needed another return
            //statement
    return "Whyyyyy?";
}

只需使用Arrays.binarySearch() 从不同的原型中可以看到,当且仅当您在数组中寻找的值不存在时,它才会返回负值。

您忘记添加退货
您是否对数组进行了排序?

if(primes[index] > a){
    return inList(Arrays.copyOfRange(primes, 0, index),a);
}
if(primes[index]<a){
   return inList(Arrays.copyOfRange(primes, index, primes.length),a);
}

在数组中查找内容的递归函数为:

public static String inList(int[] primes,int index, int a) {
    /* two breaking conditions for recursion: end of array or number found */
    if(index >= primes.length)
        return "False";

    if(primes[index] == a)
        return "True";

    /* recursion */
    return inList(primes, ++index, a);
}

您可以使用index = 0 ex调用上述方法。 inList(primes, 0, a) 这将比非递归查找方法慢得多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM