What is the essential difference between Recursion and loop?

Source: Internet
Author: User
{Code...} What is the essential difference between Recursion and loop? For example, in the above recursion, is each recursion a new scope? That is to say, $ level + 1 here is actually 0 + 1 each time, right?
Public function noLimitCategory ($ categories, $ top_id = 0, $ level = 0) {static $ arr = array (); // traverse the array foreach ($ categories as $ category) {// number of categories at the current level $ category ['level'] = $ level; if ($ category ['parent _ id'] = $ top_id) {$ arr [] = $ category; $ this-> noLimitCategory ($ categories, $ category ['id'], $ level + 1 ); // recursion} // echo'
';            //var_dump($categories);exit;            return $arr;         }

What is the essential difference between Recursion and loop? For example, in the above recursion, is each recursion a new scope? That is to say, $ level + 1 here is actually 0 + 1 each time, right?

Reply content:
Public function noLimitCategory ($ categories, $ top_id = 0, $ level = 0) {static $ arr = array (); // traverse the array foreach ($ categories as $ category) {// number of categories at the current level $ category ['level'] = $ level; if ($ category ['parent _ id'] = $ top_id) {$ arr [] = $ category; $ this-> noLimitCategory ($ categories, $ category ['id'], $ level + 1 ); // recursion} // echo'
';            //var_dump($categories);exit;            return $arr;         }

What is the essential difference between Recursion and loop? For example, in the above recursion, is each recursion a new scope? That is to say, $ level + 1 here is actually 0 + 1 each time, right?

In terms of function, all implementations implemented by recursion can be implemented by loops, but sometimes recursion is easier. In terms of efficiency, loops are generally larger than recursion.

As the landlord said, every recursion creates a new scope, andlevelIn fact, in different scopes, eachlevelAll of them are in the upper-level scope.level+1, Each timelevelThey are all different, so no0+1, TheselevelAre different variables, although they are only different variables with the same name.
Write a loop version for you, not optimized,levelIt can be not an array, so that you can understand the recursivelevelNot the samelevelWrite

Public function noLimitCategory ($ categories, $ top_id = 0, $ level = 0) {static $ arr = array (); // This static can be avoided, is it recursive? $ top_id = array (); $ level = array (); $ top_id [0] = 0; $ level [0] = 0; $ I = 0; do {foreach ($ categories as $ category) {$ category ['level'] = $ level [$ I]; if ($ category ['parent _ id'] = $ top_id [$ I]) {$ arr [] = $ category; $ top_id [] = category ['id']; $ level [] = $ level [$ I] + 1 ;}$ I ++;} while ($ I
    
     
'; // Var_dump ($ categories); exit; return $ arr ;}
    

It can be seen that if you write a loop, you need to save or differentiate it yourself.top_idAndlevelRecursion is in different scopes, so it implies differenttop_idAndlevel.

What we call low recursion efficiency means that each function call requires not only creating one moretop_idAndlevel(The above loop is just a few moretop_idAndlevel), And save the return address of each callback function call and copy it once elsewhere.categories. As I said, in the looplevelYes, it can not be used as an array, so it only needs to be allocated and saved.top_id. Therefore, the cycle efficiency is higher than recursion.

Recursion uses the stack provided by the compiler to implement this algorithm. Therefore, if you write a loop, you need to maintain the structure of this stack by yourself, in addition, you can optimize all unnecessary things (the return address of the function can be optimized) to obtain an equivalent loop version. In addition, not all programs use the stack with the highest efficiency, and this writing loop can use other data structures for optimization purposes. The problem is that the loop needs to maintain a stack by itself (this stack can be optimized in some cases), so the code is complicated.

For average people, once they learn recursion, encounter a little complicated greedy algorithm, dynamic planning, traversal, and other problems, the easiest thing to think of is recursion. From this perspective, recursive Programs are simpler (simple is what everyone can think ).

  • Loop: block-level self-repetition.

  • Recursion: function-level self-repetition.

Another essential aspect is:

  • Loop: jmp, jmp, jmp...

  • Recursion: push, push, push... pop, pop, pop...

So recursion is too deep.StackOverflow.

Recursion: each call calls itself once (which is no different from normal calls). When a function is called, The called function is pushed into the execution stack. If recursion does not return conditions, the stack will get higher and higher, and eventually cause stack overflow.

The loop is to execute a series of operations multiple times, and you can write down multiple executions in order one by one.
For example:

Var arr = [1, 2, 3]; // defines an array for (var I = 0; I

Equivalent:

console.log(arr[0]);console.log(arr[1]);console.log(arr[2]);

Recursion calls a function multiple times. Each function call generates a stack frame (stack frame in C, which should be the scope here), and the loop does not.

I feel that the subject is quite right, and the scope should be a key. However, if the scope is used only, it seems that there are some shortcomings and shortcomings. I can't tell them.
Take sorting as an example. Generally, sorting is like a bubble plug-in. Use a loop. After the previous step is executed, the next step is taken.
Literature sorting, such as quick sorting, uses recursion. I can sort myself one by two, two, four, four and eight...
From this perspective, loops can only be serialized, and Recursion can also achieve parallel performance.

Data Structure

Recursion: Stack
Loop: List

Recursively call the function itself, but the loop does not.

If the depth of the problem to be addressed is not large, I think the efficiency of recursion is similar to that of iteration. Recursion refers to the consumption of stack space, first recursion (pressure stack) and then regression (gradually release the occupied stack). If the depth of recursion is large, it will consume a lot of memory, stack Overflow may occur if no termination conditions exist. While iterations repeat some steps to release space after execution, until a termination condition, so the iteration space complexity should be lower. Generally, the conditions for iteration termination are clearly defined. I think iteration should be used as much as possible, but it is difficult to know the conditions for iteration termination like tree traversal. Instead, we can only use recursive methods to gradually approach and perform regression.

Loop is jmp recursion is push/pop

The loop structure is list, while the recursion is tree.

What is your qq account?

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.