java 代替递归,递归方法总是比Java中的迭代方法更好吗?

Are recursive methods always better than iterative methods in Java?

Also can they always be used in place of iteration and vice-versa?

解决方案

Are recursive methods always better than iterative methods in java?

No

Also can they always be used in place of iteration and vice-versa?

You can always make a recursive function an iterative one. (if memory can handle it, see interesting link here)

For some cases, it's better to use recursion (like when dealing with trees.. traveling on a binary tree.. etc..). For me, if using loops isn't more complicated and much more difficult than a recursion, I prefer to use loops.

Recursion uses more memory, but is sometimes clearer and more readable.

Using loops increases the performance, but recursion can sometimes be better for the programmer (and his performance).

So, for conclusion, deciding what to use - recursion or iteration, depends on what you want to implement, and what's more important for you (readability, performance...) and asking recursion or iteration is like asking for elegance or performance.

Example

Consider these two implementation for the factorial:

Iterative:

private int Factorial(int num)

{

int result = 1;

if (num <= 1)

return result;

while (num > 1)

{

result * = num;

num--;

}

return result;

}

Recursion:

private int Factorial(int num)

{

if (num <= 1)

return 1;

return num * Factorial(num - 1);

}

Which method is more readable?

Obviously the recursive one, it is straight forward and can be written and successfully run from the first try - It is simply translating math definition into Java!

Which method is more efficient?

Take for example num = 40, here is a time comparison:

long start = System.nanoTime();

int res = Factorial(40);

long end = System.nanoTime();

long elapsed = end - start;

System.out.println("Time: " + elapsed);

2993 for the recursive

2138 for the iterative

of course the difference will be larger when num is larger..

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值