recursion versus iteration

2023-11-04 02:48
文章标签 iteration versus recursion

本文主要是介绍recursion versus iteration,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

33 down vote favorite
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?

share | improve this question
 
3 
recursion vs iteration? iteration = for loop I think. –  gongzhitaao Mar 28 '13 at 17:13
 
Tom Moertel's blog has four excellent posts on converting recursive code to iterative code: blog.moertel.com/tags/recursion.html –  cjohnson318 Jul 24 '15 at 16:30

9 Answers 9

active oldest votes
up vote 44 down vote 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 tail call optimization, 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.

share | improve this answer
 
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. –  SomeWittyUsername Mar 28 '13 at 17:19
up vote 17 down vote

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".
share | improve this answer
 
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. –  Dukeling 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 –  SomeWittyUsername Mar 28 '13 at 17:18
 
@icepack You are right, "loops" should be plural. Thanks! –  dasblinkenlight 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. –  SomeWittyUsername Mar 28 '13 at 17:22
 
@icepack Yes, it is possible. It may not be pretty, but it's possible. –  Dukeling Mar 28 '13 at 17:23
up vote 12 down vote

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 thread 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 divide and conquer technique.

share | improve this answer
 
 
up vote 1 down vote

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

这篇关于recursion versus iteration的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/342684

相关文章

Spark MLlib模型训练—聚类算法 PIC(Power Iteration Clustering)

Spark MLlib模型训练—聚类算法 PIC(Power Iteration Clustering) Power Iteration Clustering (PIC) 是一种基于图的聚类算法,用于在大规模数据集上进行高效的社区检测。PIC 算法的核心思想是通过迭代图的幂运算来发现数据中的潜在簇。该算法适用于处理大规模图数据,特别是在社交网络分析、推荐系统和生物信息学等领域具有广泛应用。Spa

强化学习实践(二):Dynamic Programming(Value \ Policy Iteration)

强化学习实践(二):Dynamic Programming(Value \ Policy Iteration) 伪代码Value IterationPolicy IterationTruncated Policy Iteration 代码项目地址 伪代码 具体的理解可以看理论学习篇,以及代码中的注释,以及赵老师原著 Value Iteration Policy Itera

关于 python 字典报错 dictionary changed size during iteration 的理解

有时在 python 中对字典进行遍历或迭代过程中,会提示错误 dictionary changed size during iteration,这说明你对遍历或迭代的条件设置一定是错误的,你的遍历(迭代)过程在改变字典的长度(无论是删除还是增加),而你的遍历(迭代)的依据却直接来自这个字典,这是 python 不能接受的,所以会报错, 为什么说遍历(迭代)的依据直接来自字典是不可以的,

C++ Recursion(递归)的运用 及 例子

Recursion汉译为递归,其中最最重要就是函数的Recall   首先什么函数的Recall 给个例子  void print(int p){ print(p);}// 在理论上, 这个函数将会一直运行,因为一直recall自己 我们并不想一直运行一个程序,所以我们加上一点限制条件; void print(int p){ if(p==0)//在这时当p等

有关于递归函数的一些学习记录(Recursion)走楼梯,递归找出最两个数的大公约数,汉诺塔问题

递归函数的定义是指在函数执行的过程中,在函数体中直接或间接的调用了自己,这样的函数就是递归函数。递归函数的使用使得分而制之(Divide and Conquer)的思想得意实现,并在解决循环和一些复杂的求解问题中显示了很好的作用。 问题一:说,一个人在爬一个楼梯时,一次可以走一个台阶也可以走两个台阶,问这个人走到第九个台阶有多少种走法? 这是我在2013年春参加南京大学计

371.Print Numbers by Recursion-用递归打印数字(中等题)

用递归打印数字 题目 用递归的方法找到从1到最大的N位整数。 注意事项 用下面这种方式去递归其实很容易: recursion(i) {if i > largest number:returnresults.add(i)recursion(i + 1)} 样例 给出 N = 1, 返回[1,2,3,4,5,6,7,8,9]. 给出 N = 2, 返回[1,2,3,4,5,6,7,8,

loop、iterate、traversal和recursion这几个词

loop、iterate、traversal和recursion这几个词 先摘抄“为之漫笔”对这几个概念的一段理解: loop、iterate、traversal和recursion这几个词是计算机技术书中经常会出现的几个词汇。众所周知,这几个词分别翻译为:循环、迭代、遍历和递归。乍一看,这几个词好像都与重复(repeat)有关,但有的又好像不完全是重复的意思。那么这几个词到底各是什么含义,有

递归(Recursion)

递归 For some types of problems, it is useful to have functions call themselves. A recursive function is a function that calls itself either directly or indirectly through another function. Recursion

python里有类似迭代器的作用_(1条消息)Python中iteration(迭代)、iterator(迭代器)、generator(生成器)等相关概念的理解...

在阅读Python tutorial类这一章的时候出现了iterator的概念,我是一个是编程的半吊子,虽然在其它语言(比如Java和C++)中也听过这个概念,但是一直没认真的去理解,这次我参考了一些文章,总结了一些我的看法。 首先,我在理解相关的概念的时候总是试图探索引入相关概念的背后的真正意图,我们看到的多半都是用法,那么为什么要这么用,也许搞清楚了每件事情背后的目的,接下来产生的解决方案才

【Python】Recursion递归 典型问题

【Python】Recursion递归 典型问题 这里是一个刚刚上手Python的小白整理的一些题型。大部分题目来自平时上课的例题及习题,在此稍作整理,以供复习之用。 因为平时全英文,有些专有名词不知道中文名,就直接用英文代替啦~ 1. 二分法找有序数列指定值 写一个程序binary_search(x, y), 输入一个list x (你可以假设里面的数据已经按升序排列) 然后输入想要查找的