Ricorsione della coda è definita come una funzione ricorsiva in cui la chiamata ricorsiva è l'ultima istruzione eseguita dalla funzione. Quindi praticamente non rimane nulla da eseguire dopo la chiamata di ricorsione.
Ad esempio, la seguente funzione C++ print() è ricorsiva in coda.
C
// An example of tail recursive function> void> print(> int> n)> {> > if> (n <0)> > return> ;> > printf> (> '%d '> , n);> > // The last executed statement is recursive call> > print(n - 1);> }> |
>
>
C++
// An example of tail recursive function> static> void> print(> int> n)> {> > if> (n <0)> > return> ;> > cout <<> ' '> << n;> > > // The last executed statement is recursive call> > print(n - 1);> }> // This code is contributed by Aman Kumar> |
>
>
Giava
// An example of tail recursive function> static> void> print(> int> n)> {> > if> (n <> 0> )> > return> ;> > System.out.print(> ' '> + n);> > // The last executed statement> > // is recursive call> > print(n -> 1> );> }> // This code is contributed by divyeh072019> |
>
>
Python3
# An example of tail recursive function> def> prints(n):> > if> (n <> 0> ):> > return> > print> (> str> (n), end> => ' '> )> > # The last executed statement is recursive call> > prints(n> -> 1> )> > # This code is contributed by Pratham76> > # improved by ashish2021> |
>
>
C#
// An example of tail recursive function> static> void> print(> int> n)> {> > if> (n <0)> > return> ;> > Console.Write(> ' '> + n);> > // The last executed statement> > // is recursive call> > print(n - 1);> }> // This code is contributed by divyeshrabadiya07> |
>
>
Javascript
> // An example of tail recursive function> function> print(n)> {> > if> (n <0)> > return> ;> > > document.write(> ' '> + n);> > > // The last executed statement> > // is recursive call> > print(n - 1);> }> // This code is contributed by Rajput-Ji> > |
>
>
Complessità temporale: SU)
Spazio ausiliario: SU)
Necessità della ricorsione della coda:
Le funzioni ricorsive in coda sono considerate migliori delle funzioni ricorsive non in coda poiché la ricorsione in coda può essere ottimizzata dal compilatore.
I compilatori solitamente eseguono procedure ricorsive utilizzando a pila . Questo stack è costituito da tutte le informazioni pertinenti, inclusi i valori dei parametri, per ciascuna chiamata ricorsiva. Quando viene chiamata una procedura, le sue informazioni sono spinto su uno stack e quando la funzione termina le informazioni lo sono spuntato fuori dalla pila. Pertanto, per le funzioni non ricorsive in coda, the profondità della pila (quantità massima di spazio nello stack utilizzato in qualsiasi momento durante la compilazione) è maggiore.
L'idea utilizzata dai compilatori per ottimizzare le funzioni ricorsive in coda è semplice, poiché la chiamata ricorsiva è l'ultima istruzione, non c'è più nulla da fare nella funzione corrente, quindi salvare lo stack frame della funzione corrente non è di alcuna utilità (vedi questo per ulteriori informazioni dettagli).
Una funzione non ricorsiva in coda può essere scritta come ricorsiva in coda per ottimizzarla?
Consideriamo la seguente funzione per calcolare il fattoriale di n.
È una funzione non ricorsiva in coda. Anche se a prima vista sembra una coda ricorsiva. Se osserviamo più da vicino, possiamo vedere che viene utilizzato il valore restituito da fact(n-1). fatto(n) . Quindi la chiamata a fatto (n-1) non è l'ultima cosa fatta da fatto(n) .
C++
#include> using> namespace> std;> // A NON-tail-recursive function. The function is not tail> // recursive because the value returned by fact(n-1) is used> // in fact(n) and call to fact(n-1) is not the last thing> // done by fact(n)> unsigned> int> fact(unsigned> int> n)> {> > if> (n <= 0)> > return> 1;> > return> n * fact(n - 1);> }> // Driver program to test above function> int> main()> {> > cout << fact(5);> > return> 0;> }> |
>
>
Giava
class> GFG {> > // A NON-tail-recursive function.> > // The function is not tail> > // recursive because the value> > // returned by fact(n-1) is used> > // in fact(n) and call to fact(n-1)> > // is not the last thing done by> > // fact(n)> > static> int> fact(> int> n)> > {> > if> (n ==> 0> )> > return> 1> ;> > return> n * fact(n -> 1> );> > }> > // Driver program> > public> static> void> main(String[] args)> > {> > System.out.println(fact(> 5> ));> > }> }> // This code is contributed by Smitha.> |
>
>
Python3
# A NON-tail-recursive function.> # The function is not tail> # recursive because the value> # returned by fact(n-1) is used> # in fact(n) and call to fact(n-1)> # is not the last thing done by> # fact(n)> def> fact(n):> > if> (n> => => 0> ):> > return> 1> > return> n> *> fact(n> -> 1> )> # Driver program to test> # above function> if> __name__> => => '__main__'> :> > print> (fact(> 5> ))> # This code is contributed by Smitha.> |
>
>
C#
using> System;> class> GFG {> > // A NON-tail-recursive function.> > // The function is not tail> > // recursive because the value> > // returned by fact(n-1) is used> > // in fact(n) and call to fact(n-1)> > // is not the last thing done by> > // fact(n)> > static> int> fact(> int> n)> > {> > if> (n == 0)> > return> 1;> > return> n * fact(n - 1);> > }> > // Driver program to test> > // above function> > public> static> void> Main() { Console.Write(fact(5)); }> }> // This code is contributed by Smitha> |
>
>
PHP
// A NON-tail-recursive function. // The function is not tail // recursive because the value // returned by fact(n-1) is used in // fact(n) and call to fact(n-1) is // not the last thing done by fact(n) function fact( $n) { if ($n == 0) return 1; return $n * fact($n - 1); } // Driver Code echo fact(5); // This code is contributed by Ajit ?>> |
>
>
Javascript
> // A NON-tail-recursive function.> // The function is not tail> // recursive because the value> // returned by fact(n-1) is used> // in fact(n) and call to fact(n-1)> // is not the last thing done by> // fact(n)> function> fact(n)> {> > if> (n == 0)> > return> 1;> > > return> n * fact(n - 1);> }> // Driver code> document.write(fact(5));> // This code is contributed by divyeshrabadiya07> > |
>
>Produzione
120>
Complessità temporale: SU)
Spazio ausiliario: SU)
La funzione di cui sopra può essere scritta come una funzione ricorsiva in coda. L'idea è di utilizzare un ulteriore argomento e accumulare il valore fattoriale nel secondo argomento. Quando n raggiunge 0, restituisce il valore accumulato.
Di seguito è riportata l'implementazione utilizzando una funzione ricorsiva in coda.
C++
#include> using> namespace> std;> // A tail recursive function to calculate factorial> unsigned factTR(unsigned> int> n, unsigned> int> a)> {> > if> (n <= 1)> > return> a;> > return> factTR(n - 1, n * a);> }> // A wrapper over factTR> unsigned> int> fact(unsigned> int> n) {> return> factTR(n, 1); }> // Driver program to test above function> int> main()> {> > cout << fact(5);> > return> 0;> }> |
>
>
Giava
// Java Code for Tail Recursion> class> GFG {> > // A tail recursive function> > // to calculate factorial> > static> int> factTR(> int> n,> int> a)> > {> > if> (n <=> 0> )> > return> a;> > return> factTR(n -> 1> , n * a);> > }> > // A wrapper over factTR> > static> int> fact(> int> n) {> return> factTR(n,> 1> ); }> > // Driver code> > static> public> void> main(String[] args)> > {> > System.out.println(fact(> 5> ));> > }> }> // This code is contributed by Smitha.> |
>
lista collegata in Java
>
Python3
# A tail recursive function> # to calculate factorial> def> fact(n, a> => 1> ):> > if> (n <> => 1> ):> > return> a> > return> fact(n> -> 1> , n> *> a)> # Driver program to test> # above function> print> (fact(> 5> ))> # This code is contributed> # by Smitha> # improved by Ujwal, ashish2021> |
>
>
C#
// C# Code for Tail Recursion> using> System;> class> GFG {> > // A tail recursive function> > // to calculate factorial> > static> int> factTR(> int> n,> int> a)> > {> > if> (n <= 0)> > return> a;> > return> factTR(n - 1, n * a);> > }> > // A wrapper over factTR> > static> int> fact(> int> n) {> return> factTR(n, 1); }> > // Driver code> > static> public> void> Main()> > {> > Console.WriteLine(fact(5));> > }> }> // This code is contributed by Ajit.> |
>
>
PHP
// A tail recursive function // to calculate factorial function factTR($n, $a) { if ($n <= 0) return $a; return factTR($n - 1, $n * $a); } // A wrapper over factTR function fact($n) { return factTR($n, 1); } // Driver program to test // above function echo fact(5); // This code is contributed // by Smitha ?>> |
>
>
Javascript
> // Javascript Code for Tail Recursion> // A tail recursive function> // to calculate factorial> function> factTR(n, a)> {> > if> (n <= 0)> > return> a;> > > return> factTR(n - 1, n * a);> }> > // A wrapper over factTR> function> fact(n)> {> > return> factTR(n, 1);> }> // Driver code> document.write(fact(5));> // This code is contributed by rameshtravel07> > > |
>
>Produzione
120>
Complessità temporale: SU)
Spazio ausiliario: O(1)
Prossimi articoli su questo argomento:
- Eliminazione della coda
- Ottimizzazione delle chiamate in coda QuickSort (riduzione dello spazio nel caso peggiore in Log n)