递归是什么?
方法自己调用自己,因为递归比循环运行速度慢,一般不用(只有在遍历目录查找文件时才用)
递归的两种实现方式:
1、函数自己调用自己
//递归计算阶乘
public static long mul(int a) {
if(a==1) {
return 1;
}else {
return a*mul(a-1);
}
}
计算该段代码执行时间(纳秒):
//递归调用
long a1 = System.nanoTime();
System.out.println(mul(20));
long a2 = System.nanoTime();
System.out.println(a2-a1);
输出结果 :
//输出结果
2432902008176640000 //20的阶乘
54000 //执行时间(纳秒)
2、for循环方式
//循环实现阶乘计算
public static long mul2(int a) {
long mul = 1;
for(int i=1;i<=a;i++) {
mul *= i;
}
return mul;
}
计算该段代码执行时间(纳秒):
//for循环
long b1 = System.nanoTime();
System.out.println(mul2(20));
long b2 = System.nanoTime();
System.out.println(b2-b1);
输出结果 :
//输出结果
2432902008176640000 //20的阶乘
28800 //时间(纳秒)
小结:
循环实现比递归调用省一半时间。一般计算都使用for循环提高效率,只有在遍历目录时才会用递归,目的是减少代码量。
原因:
递归在不断调用的过程中需要调用到最后一个函数,最后一个函数返回1后,再依次返回结果到最初的函数并计算,时间复杂度为(2n),循环的时间复杂度为(n)。