关于布尔递归的困惑

时间:2016-01-25 13:03:14

标签: java algorithm recursion

对于这个递归方法,我绘制了一个递归跟踪来确定recTest(a,0,4)是返回true还是false。

public class Main {

    public static boolean recTest(int[] a, int i, int j){
        if(i>=j) return true;
        else if(a[i] > a[i+1]) return false;
        return recTest(a, i+1, j);

    }

    public static void main(String[] args) {

        int[] a = {3,6,8,7,9};
        System.out.println(Main.recTest(a,0,4));
        System.out.println(Main.recTest(a,1,4));
        System.out.println(Main.recTest(a,2,4));
        System.out.println(Main.recTest(a,3,4));
        System.out.println(Main.recTest(a,4,4));
    }

}

我得到了这个(当我手工完成时):

recTest(a,0,4) calls recTest(a,1,4)
recTest(a,1,4) calls recTest(a,2,4)
recTest(a,2,4) calls recTest(a,3,4)
recTest(a,3,4) calls recTest(a,4,4)
recTest(a,4,4) returns true [base case]

因此,我认为recTest(a,0,4)同样会返回true(因为"最低"递归返回true)。但它并没有。这是我在绘制后收到的输出:

false
false
false
true
true

希望能够解释这里到底发生了什么。

4 个答案:

答案 0 :(得分:4)

您的分析不在此处:

recTest(a,2,4) calls recTest(a,3,4)

由于a[2]大于a[3]recTest()会返回false,而不是再次自我调用。

您可以使用调试程序逐步查看代码,轻松发现这一点。

答案 1 :(得分:1)

会发生什么:

recTest(a,0,4) calls recTest(a,1,4)
recTest(a,1,4) calls recTest(a,2,4)
recTest(a,2,4) returns false

作为else if语句a[2] > a[3]分别满足8 > 7。这就是recTest(a,0,4)最终返回false的原因。

为了完整起见:

recTest(a,3,4) calls recTest(a,4,4)
recTest(a,4,4) returns true

答案 2 :(得分:1)

  .controller('MainCtrl', ['$route', '$routeParams', '$location', '$element',
    function($route, $routeParams, $location, $element) {
      // Works here
      console.log('MainCtrl', $element);
      this.$route = $route;
      this.$location = $location;
      this.$routeParams = $routeParams;
  }])
  .controller('BookCtrl', ['$routeParams', '$element', function($routeParams, $element) {
    // Broken here
    console.log('BookCtrl', $element);
    this.name = "BookCtrl";
    this.params = $routeParams;
  }])

答案 3 :(得分:0)

在递归之前有一个if-else语句,所以我认为你背后的理由是无效的。 将您的代码放在像Eclipse或IntelliJ这样的IDE中,并在每次迭代中查看变量的值,您会发现它非常有意义。