欢迎光临散文网 会员登陆 & 注册

递归结构的使用

2022-06-07 13:11 作者:虚云幻仙  | 我要投稿

/**
* 测试递归结构的使用
* 递归即 方法内调用该方法本身 直到达到特定条件结束套娃依次返回结果
*/

public class TestRecursion {

   public static void main(String[] args) {

       long startTime = System.currentTimeMillis();
       //读取当前时间 单位毫秒
       int a = factorial(11);
       System.out.println(a);
       //f(5)运算得 5*f(4) 等待f(4)运算结果再返回f(5)的值给a
       //f(4)运算得4*f(3)等待f(3)结果再返回f(4)的值给f(5)
       //以此类推,f(2)运算得2*f(1) 等f(1)运算 f(1)运算得1 返回给2*f(1)=2*1 f(2)得2 返回给3*f(2)
       //f(4)运算得24 返回给5*f(4) = 5*24 f(5)得120,返回结果120 赋值int a = 120
       //递归每一步都要等下一步返回结果,占用大量资源,速度比循环慢效率低

       long endTime = System.currentTimeMillis();
       System.out.println(endTime-startTime+"ms");

       endTime = System.currentTimeMillis();
       a = 1;
       for (int b = 11;b!=1;b--){
           a *=b;
       }
       System.out.println(a);
       //循环作用同递归
       startTime = System.currentTimeMillis();
       System.out.println(startTime-endTime+"ms");
   }

   static int factorial(int a){
       if(a>1){
           return a*factorial(a-1);
       }else return a;
   }

}

递归结构的使用的评论 (共 条)

分享到微博请遵守国家法律