循环和递归之间有什么实际区别 [英] What is a practical difference between a loop and recursion

查看:50
本文介绍了循环和递归之间有什么实际区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用PHP,因此本示例将使用PHP,但问题适用于多种语言.

I am currently working in PHP, so this example will be in PHP, but the question applies to multiple languages.

我正在与我的一个魔鬼一起从事这个项目,和往常一样,我们遇到了一个大问题.现在我们俩都回家了,无法解决问题.那天晚上,我们俩都找到了解决方案,只有我使用循环来解决问题,而他使用了递归.

I am working on this project with a fiend of mine, and as always we were held up by a big problem. Now we both went home, couldn't solve the problem. That night we both found the solution, only I used a loop to tackle the problem, and he used recursion.

现在,我想告诉他循环与递归之间的区别,但是我无法提出需要在常规循环上进行递归的解决方案.

Now I wanted to tell him the difference between the loop and recursion, but I couldn't come up with a solution where you need recursion over a normal loop.

我将对两者进行简化,希望有人能解释两者之间的区别.

I am going to make a simplified version of both, I hope someone can explain how one is different from the other.

请原谅我出现任何编码错误

循环:

printnumbers(1,10);

public function printnumbers($start,$stop)
{
    for($i=$start;$i<=$stop;$i++)
    {
        echo $i;
    }
}

现在上面的代码只是简单地打印出数字.

Now the code above just simply prints out the numbers.

现在让我们通过递归来做到这一点:

Now let's do this with recursion:

printnumbers(1,10);

public function printnumbers($start,$stop)
{
    $i = $start;
    if($i <= $stop)
    {
        echo $i;
        printnumbers($start+1,$stop);
    }
}

上面的方法将执行与循环完全相同的操作,但仅使用递归.

This method above will do the exact same thing as the loop, but then only with recursion.

任何人都可以向我解释使用这些方法之一有什么区别.

Can anyone explain to me what there is different about using one of these methods.

推荐答案

循环和递归在许多方面都是等效的.不需要任何一个程序,原则上您总是可以从循环转换为递归,反之亦然.

Loops and recursions are in many ways equivalent. There are no programs the need one or the other, in principle you can always translate from loops to recursion or vice versa.

在将递归转换为循环可能需要您自己操纵堆栈的意义上,递归更为强大. (尝试使用循环遍历二叉树,您会感到痛苦.)

Recursions is more powerful in the sense that to translating recursion to a loop might need a stack that you have to manipulate yourself. (Try traversing a binary tree using a loop and you will feel the pain.)

另一方面,许多语言(和实现)(例如Java)不能正确实现尾部递归.尾递归是您在函数中最后要做的事情是调用自己(例如您的示例).这种递归不必消耗任何堆栈,但是在许多语言中却需要这样做,这意味着您不能总是使用递归.

On the other hand, many languages (and implementations), e.g., Java, don't implement tail recursion properly. Tail recursion is when the last thing you do in a function is to call yourself (like in your example). This kind of recursion does not have to consume any stack, but in many languages they do, which means you can't always use recursion.

这篇关于循环和递归之间有什么实际区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆