Recursion and Iteration Differences

Source: Internet
Author: User

To borrow someone else's illustration:

Defined

Advantages

Disadvantages

Recursive

The programming skill called by the program itself is known as recursion.

1) Big problems into small problems, can greatly reduce the amount of code;

2) define an infinite set of objects with limited statements.;

3) code is more concise and clear, more readable

1) Recursive call function, waste space;

2) recursion is too deep to cause stack overflow;

Iteration

Using the original value of the variable to derive a new value of the variable, the iteration is a non-stop call B.

1) The efficiency of the iteration is high, and the running time is increased only by increasing the number of cycles;

2) No extra overhead, no increase in space,

1) not easy to understand;

2) The code is not as simple as recursion;

3) Difficult to write complex problems.

The relationship between

1) There must be iterations in the recursion, but there is not necessarily recursion in the iteration, most of them can be converted to each other.

2) can be iterated without recursion, recursive call function, waste space, and recursion too deep easily cause the stack overflow./* Relative to */

Example:

Recursive (binary query)

intFind(int *ary,int index,int len,intvalue)

{     if(len==1)//最后一个元素     {         if (ary[index]==value)return index;//成功查询返回索引         return  -1; //失败,返回-1     }     //如果长度大于1,进行折半递归查询     int half=len/2;     //检查被查值是否大于上半部分最后一个值,如果是则递归查询后半部分     if(value>ary[index+half-1])         return Find(ary,index+half,half,value);     //否则递归查询上半部分     return Find(ary,index,half,value); }

Iteration: The classic example is the summation of real numbers, such as the sum of 1-100 of all real numbers.

intv=1;

for (i=2;i<=100;i++)

{

     v=v+i;

}

Recursion and Iteration Differences

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.