Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to go from recursion to iteration

I've used recursion quite a lot on my many years of programming to solve simple problems, but I'm fully aware that sometimes you need iteration due to memory/speed problems.

So, sometime in the very far past I went to try and find if there existed any "pattern" or text-book way of transforming a common recursion approach to iteration and found nothing. Or at least nothing that I can remember it would help.

  • Are there general rules?
  • Is there a "pattern"?
like image 935
Gustavo Carreno Avatar asked Oct 01 '08 20:10

Gustavo Carreno


People also ask

How we can replace recursion with other algorithmic techniques?

Usually, I replace a recursive algorithm by an iterative algorithm by pushing the parameters that would normally be passed to the recursive function onto a stack. In fact, you are replacing the program stack by one of your own. var stack = []; stack. push(firstObject); // while not empty while (stack.

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.

How do you get out of recursion?

The best way to get out of a recursive loop when an error is encountered is to throw a runtime exception. getMemoryInfo. availMem().

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.


1 Answers

Usually, I replace a recursive algorithm by an iterative algorithm by pushing the parameters that would normally be passed to the recursive function onto a stack. In fact, you are replacing the program stack by one of your own.

var stack = []; stack.push(firstObject);  // while not empty while (stack.length) {      // Pop off end of stack.     obj = stack.pop();      // Do stuff.     // Push other objects on the stack as needed.     ...  } 

Note: if you have more than one recursive call inside and you want to preserve the order of the calls, you have to add them in the reverse order to the stack:

foo(first); foo(second); 

has to be replaced by

stack.push(second); stack.push(first); 

Edit: The article Stacks and Recursion Elimination (or Article Backup link) goes into more details on this subject.

like image 140
David Segonds Avatar answered Nov 25 '22 00:11

David Segonds