博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
recursion versus iteration
阅读量:4031 次
发布时间:2019-05-24

本文共 4948 字,大约阅读时间需要 16 分钟。

33
13

Is it correct to say that everywhere recursion is used a for loop could be used? And if recursion is usually slower what is the technical reason for ever using it over for loop iteration?

And if it is always possible to convert an recursion into a for loop is there a rule of thumb way to do it?

|
 
3  
recursion vs iteration? iteration = for loop I think. – 
Mar 28 '13 at 17:13
 
Tom Moertel's blog has four excellent posts on converting recursive code to iterative code: – 
Jul 24 '15 at 16:30

9 Answers 9

44
accepted

Recursion is usually much slower because all function calls must be stored in a stack to allow the return back to the caller functions. In many cases, memory has to be allocated and copied to implement scope isolation.

Some optimizations, like , make recursions faster but aren't always possible, and aren't implemented in all languages.

The main reasons to use recursion are

  • that it's more intuitive in many cases when it mimics our approach of the problem
  • that some data structures like trees are easier to explore using recursion (or would need stacks in any case)

Of course every recursion can be modeled as a kind of loop : that's what the CPU will ultimately do. And the recursion itself, more directly, means putting the function calls and scopes in a stack. But changing your recursive algorithm to a looping one might need a lot of work and make your code less maintainable : as for every optimization, it should only be attempted when some profiling or evidence showed it to be necessary.

|
 
5  
To add on it - recursion is closely related to the term of reduction which plays a central role in many algorithms and in CS in general. – 
Mar 28 '13 at 17:19
17

Is it correct to say that everywhere recursion is used a for loop could be used?

Yes, because recursion in most CPUs is modeled with loops and a stack data structure.

And if recursion is usually slower what is the technical reason for using it?

It is not "usually slower": it's recursion that is applied incorrectly that's slower. On top of that, modern compilers are good at converting some recursions to loops without even asking.

And if it is always possible to convert an recursion into a for loop is there a rule of thumb way to do it?

Write iterative programs for algorithms best understood when explained iteratively; write recursive programs for algorithms best explained recursively.

For example, searching binary trees, running quicksort, and parsing expressions in many programming languages is often explained recursively. These are best coded recursively as well. On the other hand, computing factorials and calculating Fibonacci numbers are much easier to explain in terms of iterations. Using recursion for them is like swatting flies with a sledgehammer: it is not a good idea, even when the sledgehammer does a really good job at it+.


+ I borrowed the sledgehammer analogy from Dijkstra's "Discipline of Programming".
|
 
2  
Recursion is usually more expensive (slower / more memory), because of creating stack frames and such. The difference may be small when applied correctly for a sufficiently complex problem, but it's still more expensive. There are possible exceptions such as tail recursion optimization. – 
Mar 28 '13 at 17:17
 
I'm not sure about a single for loop in every case. Consider a more complex recursion or a recursion with more than single variable – 
Mar 28 '13 at 17:18
 
@icepack You are right, "loops" should be plural. Thanks! – 
Mar 28 '13 at 17:21
 
@dasblinkenlight It might be theoretically possible to reduce multiple loops to a single one, but not sure about this. – 
Mar 28 '13 at 17:22
 
@icepack Yes, it is possible. It may not be pretty, but it's possible. – 
Mar 28 '13 at 17:23
12

Question :

And if recursion is usually slower what is the technical reason for ever using it over for loop iteration?

Answer :

Because in some algorithms are hard to solve it iteratively. Try to solve depth-first search in both recursively and iteratively. You will get the idea that it is plain hard to solve DFS with iteration.

Another good thing to try out : Try to write Merge sort iteratively. It will take you quite some time.

Question :

Is it correct to say that everywhere recursion is used a for loop could be used?

Answer :

Yes. This has a very good answer for this.

Question :

And if it is always possible to convert an recursion into a for loop is there a rule of thumb way to do it?

Answer :

Trust me. Try to write your own version to solve depth-first search iteratively. You will notice that some problems are easier to solve it recursively.

Hint : Recursion is good when you are solving a problem that can be solved by technique.

|
 
 
1

Besides being slower, recursion can also result in stack overflow errors depending on how deep it goes.

转载地址:http://fshbi.baihongyu.com/

你可能感兴趣的文章
Jenkins中shell-script执行报错sh: line 2: npm: command not found
查看>>
8.X版本的node打包时,gulp命令报错 require.extensions.hasownproperty
查看>>
Jenkins 启动命令
查看>>
Maven项目版本继承 – 我必须指定父版本?
查看>>
Maven跳过单元测试的两种方式
查看>>
通过C++反射实现C++与任意脚本(lua、js等)的交互(二)
查看>>
利用清华镜像站解决pip超时问题
查看>>
[leetcode BY python]1两数之和
查看>>
微信小程序开发全线记录
查看>>
Centos import torchvision 出现 No module named ‘_lzma‘
查看>>
Maximum Subsequence Sum
查看>>
PTA:一元多项式的加乘运算
查看>>
CCF 分蛋糕
查看>>
解决python2.7中UnicodeEncodeError
查看>>
小谈python 输出
查看>>
Django objects.all()、objects.get()与objects.filter()之间的区别介绍
查看>>
python:如何将excel文件转化成CSV格式
查看>>
Django 的Error: [Errno 10013]错误
查看>>
机器学习实战之决策树(一)
查看>>
[LeetCode By Python] 2 Add Two Number
查看>>