0

I have an algorithm that works perfectly, but it uses recursion. I know there are patterns for just about everything, but I could not find one for this case.

I just need some simple examples that show how to modify an algorithm, specifically the part where a method or function calls itself. I've seen iteration algorithms that do it with a while loop. So there must be a simple checklist to follow in order to convert an recursive algorithm into an iterational one.

Proud Member
  • 40,078
  • 47
  • 146
  • 231

3 Answers3

2

You can definitely model recursion with iteration and a custom call stack. Since recursion is nothing but execution of same instructions in a new environment, you can model your own environment using a simple stack structure, and just wrap your algorithm in a loop, pushing your current mini-environment at the start of an iteration and popping it whenever you finish a loop iteration, or exit it prematurely via break or continue.

yan
  • 20,644
  • 3
  • 38
  • 48
  • Correct, but determining what constitutes "your current mini-environment" isn't always trivial, especially with branching recursion. – Davy8 Apr 25 '11 at 17:34
1

BTW, if you are using GCC or llvm, then your non-debug code with -O2 or -O3 turned on will perform tail recursion elimination for you. (In case you don't know, tail recursion is when the recursion call comes last thing in the function and is simply returned, i.e. not part of an expression. See http://en.wikipedia.org/wiki/Tail_call.)

So, if the recursive write up is clearer to read, it's probably better to stick with that.

Hack Saw
  • 2,741
  • 1
  • 18
  • 33
  • 1
    Just to add, it's not simply that it's the last thing in a function, but when the return value of the call isn't used to create the current return value. i.e. `return 4+recur(i);` isn't tail-recursive since its return value is still used to produce the current return value. – yan Apr 25 '11 at 17:38
  • Thanks for the reminder, yan. +1. Edited answer to reflect this. – Hack Saw Apr 25 '11 at 17:59
1

Tail-call recursion where the recursion happens as the end of a function is pretty trivial to make non-recursive with a loop. Some compilers even do that for you automatically.

Converting any recursive function into an iterative one in a systematic way isn't so simple and in all likelihood you'd end up creating your own call stack, which most likely defeats the purpose of having a non-recursive algorithm anyway.

Also see: Can every recursion be converted into iteration?

Community
  • 1
  • 1
Davy8
  • 30,868
  • 25
  • 115
  • 173