Slippery Rock University | Dr. Deborah Whitfield | Go Browns! |
Recursion Review - Tail Recursion
void count1(int n) { if (n == 0) return; else { system.out.println(n); count1 (n-1); } }
void count2(int n) { if (n == 0) return; else { count2 (n-1); system.out.println(n); } }
Recursive Binary Search
Towers of Hanoi Revisted
if (numDisks == 1) System.out.println("Move from "+from+" to"+to); else solveTowers(int numDisks -1, from, to, temp) // O(Tn-l} System.out.println("Move from "+from+" to"+to) // O(1) solveTowers(int numDisks -1, temp, from, to); // O(Tn-l}
If (A[lowPtr] < A[highPtr]) WS[j++] = A[lowPtr++] Else WS[j++] = A[highPtr++]
N | N2 | N log2N |
---|---|---|
2 | 4 = 2*2 | 2 = 2*2 |
4 | 16 = 4*4 | 8 = 4*2 |
1024 | 1M | 1K |
106 | 1012 | 2 * 107 |
~ 220 | ~ 240 | ~ 20 * 220 |
Eliminating recursion by using stacks
The Knapsack Problem
11 | //Target = 20, 11 is too small |
11, 8 | //Target = 9, 8 is too small |
11, 8, 7 | //Target = 1, 7 is too big |
11, 8, 6 | //Target = 1, 6 is too big |
11, 8, 5 | //Target = 1, 5 is too big //No more items |
11, 7 | //Target = 9, 7 is too small |
11, 7, 6 | //Target = 2, 6 is too big |
11, 7, 5 | //Target = 2, 5 is too big //No more items |
11, 6 | //Target = 9, 6 is too small |
11, 6, 5 | //Target = 3, 5 is too big //No more items |
11, 5 | //Target = 9, 5 is too small //No more items |
8 | //Target = 20, 8 is too small |
8, 7 | //Target = 12, 7 is too small |
8, 7, 6 | //Target = 5, 6 is too big |
8, 7, 5 | //Target = 5, 5 is just right! |