Recursive Methods VS Iteration [duplicate]

3

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

    
asked by anonymous 13.11.2014 / 19:59

1 answer

3

Iterative is better than recursion when we are analyzing performance. The readability of iterative codes requires some programmer experience, especially in larger codes with many nested loops.

Recursion gives the code greater readability, making it easier to understand. For small applications, recursion often has a tolerable loss of performance. There are also techniques, such as memoizing (caching), that can equate algorithmic com- petitiveness with the iterative program.

  

link

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 1-line with ternary operator

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

Recursive methods spend more processing power. Usually uses recursive methods for solutions in which iterations are not feasible.

Here has a comparison between the two types of methods.

    
13.11.2014 / 20:03