Let's talk about recursion: Is loop and iteration the same thing?

Source: Internet
Author: User
Iterative algorithms are a basic method for solving problems with computers. It allows computers to execute a group of commands (or a certain step) repeatedly and execute these commands (or these steps) at a time by taking advantage of the high computing speed and the ability to perform repetitive operations) the original value of the variable. I personally think that iteration is a type of loop. the code of the loop body is divided into a fixed loop body and a changed loop body.

First, I would like to extract an understanding of the following concepts:

Loop, iterate, traversal, and recursion are several frequently used words in computer technology books. As we all know, these words are translated into loops, iterations, traversal, and recursion. At first glance, these words seem to be related to repeat, but some seem to be not completely repetitive. What are the meanings, differences, and connections of these words? Next I will try to explain it.

  • Loop refers to repeated execution of the same piece of code when conditions are met. For example, the while statement.
  • Iteration refers to accessing each item in the list one by one in a certain order. For example, the for statement.
  • Traversal refers to accessing each node in the tree structure according to certain rules, and each node is only accessed once.
  • Recursion refers to the behavior that a function continuously calls itself. For example, output the famous Fibonacci series programmatically.

With the above definitions, the differences between these concepts are actually clear. As for the relationship between them, strictly speaking, they all seem to belong to the scope of algorithms. In other words, they are just different ways and means to solve the problem, and they are essentially ways to achieve a specific goal in computer programming.

Iteration

Iterative algorithms are a basic method for solving problems with computers. It allows computers to execute a group of commands (or a certain step) repeatedly and execute these commands (or these steps) at a time by taking advantage of the high computing speed and the ability to perform repetitive operations) the original value of the variable.

To solve the problem using iterative algorithms, we need to do the following three aspects:

  1. Determine the iteration variable. Among the problems that can be solved by iterative algorithms, there is at least one variable that is directly or indirectly recursive from the old value to the new value. this variable is the iteration variable.
  2. Create an iteration relationship. The so-called iterative relationship refers to how to derive the formula (or relationship) of the next value from the previous value of the variable ). The establishment of the iteration relationship is the key to solving the iteration problem. it can usually be done using a recursive or inverted method.
  3. Control the iteration process. When will the iteration end? This is an issue that must be considered when writing iterative programs. The iteration process cannot be repeated endlessly. The control of the iteration process can be divided into two situations: one is that the number of iterations required is a definite value and can be calculated; the other is that the number of iterations required cannot be determined. In the previous case, you can build a fixed number of cycles to control the iteration process. in the latter case, you need to further analyze the conditions used to end the iteration process.

You can use iterative algorithms to have a classic problem, such as the Rabbit birth problem: suppose you have a female and a couple of newborn rabbits that start mating when they grow to an hour, at the end of June February, female rabbits produced another pair of rabbits. after a month, they began to breed, so they continued. Each female produces a rabbit every month when it begins to breed. If no rabbit died, how many rabbits will there be in total after one year?

There is also a question about how to go up the stairs: there are 10 levels of stairs, each step can only span one or two levels, there are several different ways to climb the 10th level steps?

For these two questions, refer to the previous article: Rabbit birth issue of interesting algorithms.

Iteration and loop

First, literally:

  • Iteration: "overlapping": rotation, rotation, replacement, alternate, and replacement. "Generation": replace. So iteration means the cycle of change, which is replaced by rotation.
  • Loop: constant repetition.

I personally think that iteration is a type of loop. the code of the loop body is divided into a fixed loop body and a changed loop body.

Fixed loop example:

for($i=0; $i < 8; $i++){echo 'Welcome to NowaMagic';}

Implementation iteration:

$sum = 0;for($i = 1; $i <= 1000; $i++ ){$sum = $sum + i;}

The above iterations are common incremental iterations. There are also progressive iteration and recursive iteration.

Iteration benefits: iteration reduces redundant code and improves the utilization and dynamics of code.

Loop, iteration, and recursion

1. the difference between a recursive algorithm and an iterative algorithm is that a function or algorithm has Convergence. it is feasible to use a recursive algorithm only when an algorithm has the expected convergence effect. otherwise, you cannot use recursive algorithms.

Of course, theoretically, all recursive functions can be converted to iterative functions, and vice versa, but the cost is usually relatively high. However, from the perspective of the algorithm structure, the structure of recursive statements cannot always be converted into an iterative structure because the extension of the structure itself belongs to the concept of recursion and the iterative method cannot be implemented at the initial stage of design, this is just like a thing with Dynamic polymorphism that can not always be implemented using static polymorphism. This is also the reason why recursive instead of iterative methods are usually used in structural design. a typical example is similar to a linked list, which uses recursive definition and its simplicity, however, the definition and call processing of memory definitions (array methods) become obscure, especially when problems such as link chains, graphs, and grids are encountered, it is unrealistic to use iteration methods from description to implementation.

2. recursion makes it easier for programmers to use machines. It can easily write programs as long as it gets mathematical formulas. It is easy to understand and program. However, recursion is implemented by the stack mechanism. each layer needs to occupy a data area of the stack. for some algorithms with deep layers of nesting, recursion will not work, space will end with memory crash, and recursion also brings about a lot of function calls, which also has a lot of additional time overhead. So when the depth is large, its time and space is not good.

The disadvantage of loop is that it is hard to understand and to compile complicated problems. The advantage is high efficiency. The running time is increased because of the increase in the number of cycles, so there is no additional overhead. There is no increase in space.

3. the memory occupied by local variables is one-time, that is, the space complexity of O (1). For recursion (without consideration of tail recursion optimization), each function call needs to be pushed to the stack, the spatial complexity is O (n), which is linearly related to the number of recursion.

4. if recursive programs are switched to loop implementation, they usually need to maintain a stack by themselves so that the status can be traced back. If a recursive program simply does not need to maintain the stack when it is switched to a loop, the writing of this recursive program is only significant and does not have to be written in a recursive form. However, many recursive programs use the auto variable of the function itself on the system stack to record the status for backtracking.

In principle, all recursion can be eliminated, at the cost of maintaining a stack. Furthermore, I personally think that recursion is necessary in many cases. it can often break down complex problems into simpler steps and reflect the nature of the problem.

Recursion is actually the process of using the system stack to call functions or call each other. In the process of connecting to the boundary, we will save the single-step address, know that the boundary is reached, and then perform operations based on the advanced and later outgoing address. this is just like loading a bucket, each time, we can only put East and West at the top of the list, but when we get them, we can make an aggressive move and finally get them. Recursive data transmission is similar. However, recursion cannot go on without limit. it must stop calling itself under certain conditions. Therefore, its boundary value should be clear. Just like loading a bucket to us, we cannot always pack it in without limitation. we must take it out at a certain time. A simple recursive process is a factorial function. you can take a look. But the recursive calculation method often determines its efficiency is very low, because data must constantly go into and out of the stack.

However, as a basic algorithm, recursion cannot be ignored.

Purely personal opinions. if you have different opinions, please contact me for discussion.

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

This article is available at http://www.nowamagic.net/librarys/veda/detail/2324.

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.