迭代和递归之间有什么区别? [英] What is the difference between iteration and recursion?

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

问题描述

迭代递归之间有什么区别,以及为什么/ when更好:

What is the difference between iteration and recursion and why/when is one better:

while (true) {
    // Iterating
}

private void recursion() {
    if (true)
        recursion(); // Recursing

    return;
}



我看到很多递归

I see a lot of recursive implementation while it could be easily done in a simple loop.

推荐答案

递归和迭代之间有两个主要的区别:相同算法的版本。

There are two main differences between Recursion and an Iterative Version of the same algorithm.

首先,有些时候,理解递归算法几乎比迭代算法更好。(至少如果你是有经验的程序员)因此它提高了表达能力,一些情况下可读性(在其他情况下也可能导致相反的情况)

First of all, some times it is almost better to understand a recursive algorithm than an iterative one (At least if you are experienced programmer) So it does increase expressivity and in some cases readability (It might also lead to the exact opposite in other cases)

Expresivity是一个巨大的编程语言,可以写5行而不是20是一个巨大的交易。

Expresivity is a huge deal on programming languages and be able to write the same code in 5 lines instead of 20 is a huge deal.

在缺点,它降低你的代码的性能。递归函数必须将函数记录保存在内存中,并从一个内存地址跳转到另一个内存地址,以便调用以传递参数和返回值。这使他们非常糟糕的性能明智。

On the downside, it decreases the performance of your code. Recursive functions have to keep the function records in memory and jump from one memory address to another to be invoked to pass parameters and return values. That makes them very bad performance wise.

汇总:

迭代算法=快速性能,有时也很难阅读)

Iterative Algorithms = Fast Performance but hard to write (sometimes hard to read too)

递归算法=写入速度快,但性能较差(有时更容易理解)

Recursive Algorithms = Fast to write but Bad performance wise (Sometimes easier to understand too)

以这个例子:

public static long fib(long n) {
    if (n <= 1) return n;
    else return fib(n-1) + fib(n-2);
}

vs

    if ((n == 1) || (n == 2)) {
        return 1;
    } else {
        long prev = 1, current = 1, next = 0;
        for (long i = 3; i <= n; i++) {
            next = prev + current;
            prev = current;
            current = next;
        }
        return next;
    }

资料来源:

http://www.csd.uwo.ca/Courses/CS1027a/code/FibonacciDemo.java

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

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