Recursion: the efficiency of recursion

Source: Internet
Author: User
Recursion simplifies the way we think when solving some problems, and the code is more refined and easy to read. So since recursion has so many advantages, should we solve all the problems with recursion? Does recursion have no disadvantages? Today we will discuss the shortcomings of recursion. When talking about recursion, we have to deal with its efficiency.

Recursion simplifies the way we think when solving some problems, and the code is more refined and easy to read. So since recursion has so many advantages, should we solve all the problems with recursion? Does recursion have no disadvantages? Today we will discuss the shortcomings of recursion. When talking about recursion, we have to deal with its efficiency.

Why is recursion inefficient?

Let's take the Fibonacci series as an example. In many textbooks or articles that involve recursion or computational complexity, the program for calculating the Fibonacci series is used as a classic example. If you want to use C # to write a function that calculates the Nth Number of the Fibonacci series at the fastest speed (ignore exceptions such as parameter less than 1 or result overflow ), I don't know if your program will be similar to the following code:

public static ulong Fib(ulong n){    return (n == 1 || n == 2) ? 1 : Fib(n - 1) + Fib(n - 2);}

This piece of code should be short and concise (only one line of code is executed), intuitive and clear, and very compliant with the Code Aesthetics of many programmers. it may be quite confusing for many people to write such code during interviews. However, if you use this code to calculate Fib (1000), I think it will never be better. its running time may drive you crazy.

It seems that good-looking code may not be used. if the program is unable to accept the efficiency, the beautiful things will be cloudification. If you analyze the execution stream of the program, you will find the problem. take the calculation of Fibonacci (5) as an example:

We can see that in the calculation of Fib (5), Fib (1) is calculated twice, Fib (2) is calculated three times, Fib (3) after two computation, nine computation is performed for only five computation tasks. This problem will become more and more prominent as the scale increases, so that Fib (1000) can no longer be calculated within an acceptable period of time.

We used a simple definition to calculate fib (n), that is, the formula fib (n) = fib (n-1) + fib (n-2 ). This idea is easy to think of, but a careful analysis we found that when calling fib (n-1), also call fib (n-2), that is, fib (n-2) two calls, the same principle, when calling f (n-2) f (n-3) also called twice, and these redundant calls are completely unnecessary. The complexity of this algorithm can be calculated exponentially.

Improved Fibonacci recursive algorithm

So is there a better recursive algorithm for calculating the Fibonacci series? Of course. Let's take a look at the first few items of the Fibonacci series:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55 …

Note No. if we remove the previous item, the resulting sequence still satisfies f (n) = f (n-1)-f (n-2), (n> 2 ), the sequence we get starts with 1 or 2. It is easy to find that the N-1 of this series is the nth of the original series. How do we know how to design algorithms? We can write a function that accepts three parameters. The first two are the first two of the series, the third is the number of columns starting with the previous two parameters.

int fib_i(int a, int b, int n);

In the function, we first check the value of n. If n is 3, we only need to return a + B, which is a simple situation. If n> 3, we call f (B, a + B, n-1 ), in this way, the problem scale is reduced (from the nth to the n-1 ). The final code is as follows:

int fib_i(int a, int b , int n){    if(n == 3)        return a+b;    else        return fib_i(b, a+b, n-1);}

The resulting algorithm complexity is O (n. It is linear. Its efficiency can be compared with the efficiency of iterative algorithms. However, it is not economical because function calling is still performed repeatedly.

Efficiency Comparison between recursion and iteration

We know that recursive calls are actually called by the function itself, and the function call overhead is very large. The system needs to allocate storage space for each function call, record the call point pressure stack. After the function call is complete, you need to release the space and resume the breakpoint through the stack. Therefore, function calling is not only a waste of space, but also time.

In this way, we find that if the complexity of the recursive solution is not significantly higher than that of other solutions, it is not cost-effective to use recursion. Because it wastes a lot of time on processing function calls. The concept of inline functions is introduced in C ++ to avoid the decrease in efficiency caused by the execution time of simple functions being less than the function call time. This is also a truth. if too much time is used for processing function calls, the efficiency is obviously not high.

For example, for a factorial function, the time complexity of its iteration algorithm is O (n ):

int fact(n){    int i;    int r = 1;    for(i = 1; i < = n; i++)    {        r *= i;    }    return r;}

The time complexity of the recursive function is O (n ):

int fact_r(n){    if(n == 0)        return 1;    else        return n * f(n);}

However, recursive algorithms require n function calls, while iterative algorithms only require n iterations. The efficiency difference is significant.

Summary

From the above analysis, we can see that recursion calls functions repeatedly when dealing with problems, which increases the space and time overhead of the functions. Therefore, iteration can easily solve the problems, recursion can simplify the thinking process, but it is inefficient. Efficiency and overhead are the biggest disadvantages of recursion.

Although there are such shortcomings, the strength of recursion is huge and cannot be ignored, because it is difficult or even impossible to solve some problems (such as the Tower of Hanoi problem) by using iterative algorithms ). At this time, the role of recursion is displayed.

The efficiency of recursion is currently discussed here. The recursive and iterative computing processes will be introduced later.

Additional reading

The topic list of this article is as follows:

  1. Recursive: recursive thinking
  2. Recursion: two conditions that must be met by recursion
  3. Recursion: recursive determination of string-to-text phenomena
  4. Recursive: recursive implementation of binary search algorithms
  5. Recursion: the efficiency of recursion
  6. Recursion: recursion and loop
  7. Let's talk about recursion: Is loop and iteration the same thing?
  8. Recursive computing and iterative computing
  9. On Recursion: Learn about tail recursion from Fibonacci
  10. Recursive: Tail recursion and CPS
  11. Recursion: add more knowledge about Continuation.
  12. Recursion: Tail recursion in PHP and its optimization
  13. Recursion: Tail recursion optimization from the perspective of Assembly

Address: http://www.nowamagic.net/librarys/veda/detail/2321,welcome.

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.