Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between iteration and recursion?

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

while (true) {
    // Iterating
}

And

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.


1 Answers

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 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.

Sum Up:

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)

Take this example:

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;
    }

Source:

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

like image 96
Iordanis Avatar answered Sep 14 '25 19:09

Iordanis