递归方法执行顺序的小实验

文章通过代码示例解释了递归调用的过程,特别是针对分治法中的二分排序算法。递归执行遵循先执行非递归部分,然后进行递归调用的顺序。同时,通过斐波那契数列的递归实现,展示了递归如何形成类似二叉树的结构,类比为前序遍历的方式。
摘要由CSDN通过智能技术生成

该文章仅用于一个小知识点的提醒,以免忘记。

对于任何语言函数内执行递归时的执行顺序都是一样的。先执行递归前的所有内容,再执行递归后的所有内容。而对于多递归的分治法执行就相当于树一样。

例:

package sortingAlgorithm;

public class Test {
    public static void test(Integer[] arr, int start, int end){
        System.out.println("start:"+start+"; "+"end:"+end);
        if(start >= end){
            System.out.println("结束递归");
            return;
        }
        int mid = (start+end)/2;
        System.out.println(mid);
        System.out.println("执行第一个test递归前");
        test(arr, start, mid);  //递归二分数组的第一个
        System.out.println("执行第一个test递归后");
        test(arr, mid+1, end);
        System.out.println("执行the second递归后");

    }

    public static void test(Integer[] arr){
        int length = arr.length;
        test(arr, 0, length-1);
    }

    public static void main(String[] args) {
        Integer[] array = {5,3, 6, 4, 2, 1, 7, 8, 10, 4, 2};
        test(array);
    }
}

>>>main()
start:0; end:10
5
执行第一个test递归前
start:0; end:5
2
执行第一个test递归前
start:0; end:2
1
执行第一个test递归前
start:0; end:1
0
执行第一个test递归前
start:0; end:0
结束递归
执行第一个test递归后
start:1; end:1
结束递归
执行the second递归后
执行第一个test递归后
start:2; end:2
结束递归
执行the second递归后
执行第一个test递归后
start:3; end:5
4
执行第一个test递归前
start:3; end:4
3
执行第一个test递归前
start:3; end:3
结束递归
执行第一个test递归后
start:4; end:4
结束递归
执行the second递归后
执行第一个test递归后
start:5; end:5
结束递归
执行the second递归后
执行the second递归后
执行第一个test递归后
start:6; end:10
8
执行第一个test递归前
start:6; end:8
7
执行第一个test递归前
start:6; end:7
6
执行第一个test递归前
start:6; end:6
结束递归
执行第一个test递归后
start:7; end:7
结束递归
执行the second递归后
执行第一个test递归后
start:8; end:8
结束递归
执行the second递归后
执行第一个test递归后
start:9; end:10
9
执行第一个test递归前
start:9; end:9
结束递归
执行第一个test递归后
start:10; end:10
结束递归
执行the second递归后
执行the second递归后
执行the second递归后

图解分析如下:

更加清晰点的树性递归可以用斐波那契测试:

public class Test {

    private int fibonacci(int n){
        if (n == 0 || n ==1){
            System.out.println(n);
            return 1;
        }
        System.out.println(n);
        return fibonacci(n-1)+fibonacci(n-2);
    }

    public static void main(String[] args) {
        Test test = new Test();
        int ans = test.fibonacci(5);
        System.out.println("Ans:"+ans);
    }
}
>>>main()
5
4
3
2
1
0

1

2
1
0

3
2
1
0

1

Ans:8

图解如下:

总结:

可从输出结果得出:递归相当于二叉树的前序遍历,根节点→左树节点→右树节点。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值