From Recursion To Iteration: A Case Study COMP 212 Spring 2007
ASorter’s sort() method public final void sort(Object[] A, int lo, int hi) { if (lo < hi) { int s = split(A, lo, hi); sort(A, lo, s-1); sort(A, s, hi); join(A, lo, s, hi); }
A Pathological Case size = n A: sort sort size = n -1 size = 1 sort …
How Does Recursion Work? Method Execution Stack main Stack frame: sort sort sort Method parameters, Local variables, Who called whom split
Solutions? Tail-recursion elimination Iteration …
Tail Recursion int fibHelper(int i, int current, int next) { if (i == 0) return current; else return fib(i - 1, next, current + next); } int fib(int i) { return fibHelper(I, 0, 1);