A ramble on recursion and iteration

Source: Internet
Author: User
Tags repetition

Recursion (recursion) in computer science refers to a method of solving a problem by repeatedly decomposing the problem into sub-problems of similar problems. Can greatly reduce the amount of code. The ability to recursion is to define an infinite set of objects with limited statements. Recursive methods can be used to solve a lot of computer science problems, so it is a very important concept in computer science. Most programming languages support self-invocation of functions in which functions can be recursive by invoking themselves. Computational theory can prove that recursion can completely replace loops, so in many functional programming languages it is customary to use recursive returns to implement loops.

and repetition is closely related to recursion , in the recursive technique, the concept is defined directly or indirectly by itself. For example, we can define a table with a description such as "table is either empty or one element followed by a table." Recursion is supported in many programming languages. In C, function F can call itself, either directly from the function body of F , or through a series of function calls, and ultimately indirectly called F. Another important thought-induction, is closely related to "recursion", and is often used in mathematical proofs.

There are two points to note when using recursion:

1) recursion is the invocation of itself in a process or function;

2) When using recursion, there must be a definite recursive end condition called a recursive exit.

Recursion is divided into two stages:

1) Recursion: The solution of the complex problem is pushed to a simpler problem than the original problem;

2) Regression: When the simplest case is obtained, the return is gradually followed by the solution of the complex.

Fibonacci sequence

1 intFibintN)2 3 {  4 5    if(0 = =N)6 7        return0; 8 9    if(1 = =N)Ten  One        return1;  A  -    if(N > 1)   -  the        returnFIB (n-1) +fib (n-2);  -  -}

The above is a simple recursive call, because recursion causes a series of function calls, and there may be a series of repeated calculations, recursive algorithm execution efficiency is relatively low.

The recursive invocation is actually the function itself calling itself, and the call cost of the function is very large, the system wants to allocate storage space for each function call and record the call point pressure stack. At the end of the function call, the space is freed and the breakpoint is resumed. So, a function call is not just a waste of space, but a waste of time.

Iteration (interation) is the repetition of a set of instructions (or a certain step) in a program. It can be used as a generic term (synonymous with "repetition"), or it can be used to describe a particular form of repetition with a mutable state.

The power of a computer comes from its ability to repeatedly perform the same task or different versions of the same task. In the area of computing, the topic of iteration occurs in many forms. Many concepts in the data model, such as tables, are some form of repetition, such as "a table is either empty, or an element is connected to an element, followed by an element, and so forth." Using iterations, programs and algorithms can perform repetitive tasks, such as "perform the next step 1000 times," without requiring a large number of similar steps to be specified separately. The programming language while for implements the iterative algorithm using a looping structure like the statements and statements in the C language.

Compared to iterations, it's easier to solve these problems recursively, and it's easier for others to understand your code. But recursion has its own problem, each recursive basic need to apply for a new space on the stack, if you do a good job with a recursive explosion of a stack is not very difficult thing, in addition, the individual thinks that recursion relative to the iteration and the computer itself design principle some do not match, the same function recursion should be slower.

There is a way to calculate factorial, where the function of calculating factorial is defined using a recursive function:

1 func factorial (n:int), Int {2     if n = = 0 {3          Return 14    }5     return n * factorial (n-1)6  }

Now we are trying to describe the computational process of this function, taking factorial (5) as an example, and substituting the computational process step-by-step. We can see a shape that gradually expands and then shrinks. In the unfolding phase, this calculation process constructs a chain of deferred operations (here is a chain of multiplication), and the contraction process is manifested in the actual execution of these operations. Its shape can be depicted as the following legend:

  1  (factorial 5)   2  (5 * (factorial 4)   3  (5 * (4 * (FAC Torial 3))   4  (5 * (4 * (3 * (factorial 2  5  (5 * (4 * (3 * (2 * (factorial 1 6  (5 * (4 * (3 * (2 * 1  7  (5 * (4 * (3 * 2))   8  (5 * (4 * 6
       
        9  (5 * 24
        10  
      

Such a calculation process is a recursive calculation process. The recursive calculation process is characterized by a deferred operation chain, in which the interpreter needs to maintain the trajectory of the operations to be performed later, to perform the recursive calculation process.

This difference is important for computers. In the case of iterations, any point in the calculation process, a fixed number of state variables provides a complete description of the state of the calculation. Describing a recursive calculation process requires some "implicit" information, which is not stored in the program variable, but is maintained by the interpreter, indicating where the calculation process is located in the chain formed by the deferred operation (the interpreter maintains the operational chain and needs to use a data structure called a stack). The longer the chain, the more information you need to keep.

The recursive computation process, usually easy to understand, conforms to the human thinking habit. However, due to the need to use the stack mechanism implementation, its spatial complexity is usually very high. For some computation of recursive layer depth, the computer will be overwhelmed, and the space will end up with memory crashes. And recursion also brings a lot of function calls, which also has a lot of extra time overhead. So when the depth is large, it's time complexity and space complexity are not good.

Iterative algorithm is a basic method to solve the problem by computer. It takes advantage of the speed of computer operation, is suitable for the characteristics of repetitive operation, so that the computer to a set of commands (or a certain number of steps) repeated execution, each time the set of commands (or steps), the original value of the variable to exit its new value. Using an iterative algorithm to solve the problem requires doing the following three things:

(1) Determine the iteration variable. In a problem that can be solved with an iterative algorithm, there is at least one variable that, directly or indirectly, is continuously introduced with the new value by the old value, which is the iteration variable.

(2) Establish an iterative relationship. An iterative relationship is a formula (or relationship) that introduces its next value from the previous value of a variable. The establishment of iterative relationships is the key to solving the problem, which can often be accomplished using either recursive or backward methods.

(3) control the iterative process. When does the iteration process end? This is an issue that must be considered in writing an iterative procedure. You cannot allow iterative processes to repeat indefinitely. The control of an iterative process can usually be divided into two situations: one is that the desired number of iterations is a definite value that can be calculated, and the other is that the number of iterations required cannot be determined. In the former case, a fixed number of loops can be constructed to control the iterative process, and in the latter case, the conditions for ending the iterative process need to be further analyzed.

Recursion is a powerful tool for designing and describing algorithms, and the algorithm that can be used to describe the algorithm usually has this characteristic: in order to solve the problem of scale N, we try to decompose it into smaller problems, and then construct the solution of big problem conveniently from the solution of these small problems. And these smaller problems can be decomposed and synthesized in the same way, decomposing into smaller problems and constructing solutions to larger problems from the solutions of these smaller problems. In particular, when scale is n=1, it can be solved directly.

Recursion and regression are two stages in the execution of recursive algorithm. In the recursive phase, the solution of the more complex problem (size n) is solved by the problem that is simpler than the original problem (the size is less than n). For example, in the example above, solve FIB (n) and push it to solve FIB (n-1) and fib (n-2). That is, in order to calculate FIB (n), the FIB (n-1) and fib (n-2) must be computed, while the FIB (n-1) and fib (n-2) must be computed, and then the (n-3) and fib (n-4) should be calculated first. And so on, until the FIB (1) and fib (0) are calculated, respectively, the results 1 and 0 can be obtained immediately. In the recursive phase, there must be a case for terminating the recursion. For example, in a function fib, when n is 1 and 0.

In the regression phase, when the solution of the simplest case is obtained, the solution of the slightly complex problem is obtained, such as the FIB (1) and fib (0), and the results of the FIB (2) are returned. After the results of FIB (n-1) and fib (n-2) are obtained, the results of FIB (n) are returned.

When writing a recursive function, it is important to note that local variables and parameter knowledge in functions are limited to the current call layer, and when recursion is pushed into the "simple problem" layer, the original level parameters and local variables are concealed. In a series of "simple problem" layers, they each have their own parameters and local variables.

Because recursion causes a series of function calls, and there may be a series of repeated computations, the execution efficiency of the recursive algorithm is relatively low. When a recursive algorithm can be easily converted into recursive method, the program is usually programmed by recursive method. For example, the function fib (n), which computes the nth term of the Fibonacci sequence, should use a recursive algorithm that starts with the first two entries of the Fibonacci sequence and calculates the next item from the first two successive entries until the nth item of the requirement is calculated.

Reference

http://note.zqguo.com/archives/301

http://www.ituring.com.cn/tupubarticle/5504#

http://lincode.github.io/Recursion-Iteration/

Http://www.bianceng.cn/Programming/sjjg/200901/11200.htm

A ramble on recursion and iteration

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.