a recursive function may be converted to an iterative one by using a stack
think on how a function call works:
- store the program counter(PC) into the stack
- push the parameters of the function into the stack
- change the PC to the address of the function
- the function retrieve its parameters from the stack
- do whatever it has to do
- retrieves the PC from the stack
- push the return value onto the stack
- writes the PC so it returns to the caller
you may see this by doing a backtrace on your debugger.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
def T(n):
if n == 1: //base case
return 1
else: //recursive case
return T(n//2) + T(n//2) + n
def emulating_recursion(n):
s = stack new
s push: n //push the parameter
result = 0
s empty? whileFalse: //function "body"
x = s top //retrieve the parameter
s pop
if x == 1: //base case
result += 1
else: //recursive case
result += x
s push: x/2 //recursion T(n/2)
s push: x/2
return result
| |
now, I cheated there
instead of pushing the return value, I simply add it to `result', and may only do that because your recursion only invokes addition
here's an implementation where it pushes the return value, using a flag to differentiate them from parameters
https://stackoverflow.com/questions/9831666/how-can-you-emulate-recursion-with-a-stack