On recursion and tail recursion (tail recursive)

Source: Internet
Author: User

First, recursion

To put it simply, the idea of recursion is to break the problem down into smaller scale problems with the same solution as the original problem. For example, the binary search algorithm is to keep the size of the problem smaller (half of the original problem), and the new problem has the same solution as the original problem.

In general, there are two conditions that can be solved with a recursive return:

    • The problem size can be narrowed by recursive invocation, and the new problem has the same form as the original problem.
    • There is a baseline scenario (that is, egress) that allows recursion to exit in a baseline scenario.

to calculate n! For example, the recursive algorithm is:

public static long factorial(long N) {

???????? if (n==1) {

???????????? return 1;

????????}

???????? return nfactorial(n-1);

????}

?

Some problems using traditional iterative algorithms is difficult to solve even without and recursion can be easily solved, such as the Hanoi Tower problem. Recursion makes the program structure clear and understandable, but recursion also has its disadvantage. Because recursive calls are actually functions that call themselves, activation record frame stack ) (stores the current variables of the function, Information such as the return address) is pressed into the stack. When called multiple times, the constant pressure stack, it is easy to cause the stack overflow. and at the end of the function call, Also to free up space, bounce back breakpoints. This is not only a waste of space, but also a waste of time.

As a result, programmers often implement the original version recursively, then optimize it and rewrite it as a loop to improve performance. The end of recursion is entered into the eyes of people.

Second, tail recursion

This recursive invocation is the tail recursion when the recursive call is the last executed statement in the body of the function and its return value is not part of an expression. The feature of the tail recursive function is that it is not necessary to do anything in the regression process, the recursive result can be returned directly, this feature is very important, because most modern compilers will use this feature to automatically optimize the code (through the Loop method). When the compiler finds that it's not going to create a new stack frame at the end of the recursion, But constantly to cover the current stack frame, one to prevent the stack overflow, and secondly save time, with the "algorithm fine solution" inside the exact words are: "When a compiler detects a call it is tail Recursive, it overwrites the current activation record instead of pushing a new one onto the stack. " java c# " Span style= "font-family: Song body; Background-color:white "> and python

the above calculation n! the normal recursive algorithm is rewritten as the tail recursion method:

public static long factorial(long N, Long a) {

???????? if (n==1) {

???????????? return A;

????????}

???????? return factorial(n-1, n*a);

????}

?

parameters in the function a Accumulator , it is customary to translate the accumulator, in fact, not necessarily is " plus "

Third, the common recursive rewrite for the tail recursion

The key to finding a suitable accumulator is to rewrite the normal recursion to tail recursion. We show how to rewrite the normal recursion to be a tail recursion, for example, by calculating the Fibonacci sequence (Fibonacci) . The first two entries of the Fibonacci sequence are 1, starting with the third item, each of which is the same as the preceding two items. The following is the recursive algorithm given by its definition:

public static long Fibonacci (long N) {

???????? if (n<=2) {

???????????? return 1;

????????}

???????? return Fibonacci(n-1) +fib(n-2);

????}

?

The complexity of the algorithm is o (2N) fib (n-1) fib (n-2) do not calculate anything more than once "

We found that when calculating each item, we need to know the first two items, so we have two accumulators here, using the accumulator's tail recursion algorithm:

public static long Fibonacci (long N, Long A,long b) {

???????? if (n==1) {

???????????? return A;

????????}

???????? return Fibonacci(n-1, B, a+b);

????}

?

in n=5 as an example, a=1 , b=1 represents the first to second item of the sequence, respectively:

Fibonacci (5,1,1)

->fibonacci (4,1,2)

->fibonacci (3,2,3)

->fibonacci (2,3,5)

->fibonacci (1,5,8)

at this time Span style= "Font-family:times New Roman; Background-color:white ">a=5 b=8 a value 5 n!

It is easy to change the tail recursion to a non-recursive loop, as follows:

public static long Fibonacci (long n ) {

???????? int a=1,b=1;

???????? int temp=0;

???????? while (n>1) {

???????????? Temp=b;

???????????? B=a+b;

???????????? A=temp;

???????????? n--;

????????}

???????? return A;????????

????}

?

Iv. Summary

because Java The compiler does not support automatic optimization of tail recursion, and if the problem is solved by iterative methods, we'd better not let the program carry the tail recursion.

On recursion and tail recursion (tail recursive)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.