Iteration VS Recursive Methods

Asked

Viewed 4,628 times

4

What is the difference between recursive methods and iteration and what are the advantages of using the two approaches in a java program?

  • I think it has already been answered here: http://answall.com/q/21551/101

1 answer

3


Iterativity It’s better than recursive when we’re analyzing performance. Readability of iterative codes requires some programmer experience, mainly in larger code, with many nested loops.

Recursiveness gives the code greater readability, making it simpler to understand. For small applications, recursion often presents tolerable loss of performance. There are also techniques, such as memoizing (caching), that can equate the algorithmic compexity to the iterative program.

https://dietkx.wordpress.com/2009/03/09/recursividade-x-iteratividade/

Example using Iteration

int FibonacciIterativo(int termo) {
    int termo1 = 1, fibo = 0, temp = 0;
    for (int cont = 1;cont <= termo-1; cont++) {
        temp = fibo; //faz o giro, a variável temp serve somente para que não sejam perdidos valores
        fibo += termo1; //observe, são necessárias 3 variáveis
        termo1 = temp;
    }
    return fibo;
}

Example using Recursion

int FibonacciRecursivo(int termo){
   int primeiro = 0, segundo = 1, retorno = -2;
   if(termo == 1)
       retorno = primeiro;
   else if (termo == 2)
       retorno = segundo;
   else
       retorno = FibonacciRecursivo(termo-1) + FibonacciRecursivo(termo-2);
   return retorno;
}

Recursive in 1 line with ternary operator

int FibonacciRecursivoComOperadorTernario(int termo) {
    return (termo == 1 || termo == 2) ? 1 : FibonacciRecursivoComOperadorTernario(termo - 1) + FibonacciRecursivoComOperadorTernario(termo - 2);
}

Recursive methods use more processing resources. Typically uses recursive methods for solutions where iterations are not feasible.

Here has a comparison between the two types of methods.

  • Thank you. Your explanation was very clear.

  • The FibonacciRecursivo and the FibonacciRecursivoComOperadorTernario perform in exponential time, being much worse than the iterative alternative. It is possible to rewrite them in a way that maintains linear runtime without sacrificing recursiveness or readability. If you leave like this, there will be people copying this code without knowing the big problem that it has.

  • What would that be?

  • Use memoizing, or else overload with the FibonacciRecursivo where the return is an array of size 2, where one of the elements is reused.

  • So, I mentioned these methods in the answer, I just didn’t explain... I’m going to give an increment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.