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)
int
Find(
int
*ary,
int
index,
int
len,
int
value)
{
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.
int
v=1;
for
(i=2;i<=100;i++)
{
v=v+i;
}
Recursion and Iteration Differences