Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design patterns for converting recursive algorithms to iterative ones

Are there any general heuristics, tips, tricks, or common design paradigms that can be employed to convert a recursive algorithm to an iterative one? I know it can be done, I'm wondering if there are practices worth keeping in mind when doing so.

like image 723
fbrereto Avatar asked Oct 11 '09 05:10

fbrereto


People also ask

How do you convert recursive to iterative?

From this, we formulate the general rules of conversion: Use the negation of the base-case condition as the loop's condition. Use the recursive function's body (except the recursive call) as the body of the while-loop. After the loop, apply the base-case update of the accumulator and return its value.

What is used to convert recursive to iterative implementation of an algorithm?

Which data structure is best suited for converting recursive implementation to iterative implementation of an algorithm? Explanation: Since function calls are executed in Last In First Out order, stack is the data structure for converting recursive to iterative implementation.

Can you always replace recursive with iterative?

Can you always turn a recursive function into an iterative one? Yes, absolutely, and the Church-Turing thesis proves it if memory serves. In lay terms, it states that what is computable by recursive functions is computable by an iterative model (such as the Turing machine) and vice versa.

Can all program written with recursion be able to convert to iteration?

Yes, you can code recursive functions as iterations.


2 Answers

You can often entirely preserve the original structure of a recursive algorithm, but avoid the stack, by employing tail calls and changing to continuation-passing, as suggested by this blog entry. (I should really cook up a better standalone example.)

like image 72
Brian Avatar answered Oct 03 '22 05:10

Brian


A common technique that I use where I'm on the process of replace a recursive algorithm by an iterative one is generally to use a stack, pushing the parameters that are being passed to the recursive function.

Check the following articles:

  • Replacing Recursion With a Stack
  • Stacks and Recursion Elimination (pdf)
like image 21
Christian C. Salvadó Avatar answered Oct 03 '22 06:10

Christian C. Salvadó