Using a stack for recursive routines
- We know that the runtime stack is where we place activation records
- Return address
- Parameters
- Local Variables
- Copies of registers (save values)
- When we write recursive routines, we are really just using the stack
- At some point in the computation we must push the current state onto the stack
- Start a new computation
- For example:
- xn
- If n = 0, return 1
- Otherwise return x*xn-1
- In this case, we are just pushing x onto the stack n-1 times.
-
- We could handle the stack ourselves.
-
- We just loop, while n > 0, and push x onto the stack.
- In general we will need to loop while the stack is not empty
- Push the current state onto the stack
- Or alternatively, push future calls into a queue
- Work on the next state.
- We could do this to a number of algorithms we have studied sofar
- Merge sort - just put start and stop positions on the stack
- quicksort - again, start and stop positions for subarray to sort
- floodfill - put coordnates to fill
- Some examples