简体   繁体   English

线性递归如何工作?

[英]How does Linear Recursion work?

I have written a java program to add elements in an array using Linear Recursion. 我编写了一个Java程序,使用线性递归在数组中添加元素。 The output obtained is not as expected. 获得的输出与预期不符。 Can anyone point what is wrong with this program? 谁能指出这个程序有什么问题吗?

public class TestSum {

    public int count = 0;


    public int sum(int[] a){

        count++;

        if(a.length == count){
            return a[count -1];
        }

        return sum(a) + a[count -1] ;
    }

    public static void main(String[] args) {

        int[] a = {1,2,3};

        int val = new TestSum().sum(a);
        System.out.println(val);
    }

}

I am expecting the output as 6 but obtained is 9 . 我期望输出为6但获得的是9 What is wrong? 怎么了?

Strangely if I change the order of addition ie return a[count -1] + sum(a); 奇怪的是,如果我改变加法顺序,即return a[count -1] + sum(a); then it gives output as 6 . 然后给出输出为6

Generally, recursive programs that are not re-entrant (ie relying on external state) are suspicious. 通常,不重入的递归程序(即依赖外部状态)是可疑的。 In your particular case count will change between invocations of sum , making the behavior hard to trace, and ultimately resulting in the error that you observe. 在您的特殊情况下, count将在sum调用之间发生变化,从而使行为难以跟踪,最终导致您观察到错误。

You should pass the index along with the array to make it work: 您应该将索引与数组一起传递以使其工作:

// The actual implementation passes the starting index
private static int sum(int[] a, int start){
    if(a.length == start){
        return 0;
    }
    return sum(a, start+1) + a[start];
}
// Make sure the method can be called with an array argument alone
public static int sum(int[] a) {
    return sum(a, 0);
}

Unlike an implementation that increments the count external to the method, this implementation can be called concurrently on multiple threads without breaking. 与增加方法外部计数的实现不同,此实现可以在多个线程上并发调用而不会中断。

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

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