Lecture 4 - Recursion
Solving Recurrences:
- Substitution: Recursion Tree/ Telescoping
- Master Theorem (monotonic, increasing, polynomial - NOT sin(n) or 2^n)
Counting Steps
int myFunc( // 1 step
char*p,
int aN,
int ar[]) { // 1 + 1 + 1 = 3 steps
...
return
zzz; 1 + 1 = 2 steps
} // myFunc()
char *course = "EECS281"; // 8 steps to copy chars at runtime
int HWKs[4] = {100, 100, 120, 140}; // 4 steps to copy parameters at runtime?
int retCode =
myFunc( // 1 step call, 1 step return = 2 steps
course, 4, HWKs); // 3 steps for parameters, 1 step return = 4 steps
Step-counting for Recursion
int factorial (int n) {
return (n ? n * factorial(n - 1) : 1);
} // factorial ()
int factorial (int n) { // 2 steps
if (n == 0) // 1 step
return 1; // 2 steps
return n * factorial (n - 1); // 6 steps
} // factorial()
$$\begin{cases} c{0} & n == 0 \ T(n-1) + c{1} & n > x \end{cases}$$
Sample Recurrence Relation for Factorial (using Latex)
http://tex.stackexchange.com/questions/32140/how-to-write-a-function-piecewise-with-bracket-outside
\begin{cases}
c_{0} & n == 0 \\
T(n-1) + c_{1} & n > x
\end{cases}
$$T(n) = \begin{cases} c{0} & n == 0 \ T(n-1) + c{1} & n > x \end{cases}$$
Power (x^n) using Recursion (non-tail), O(n)
// O(n) complexity
int power2(int x, unsigned n) {
if (n == 0)
return 1;
return x * power2(x, n - 1);
}
$$T(n) = \begin{cases} c{0} & n == 0 \ T(n-1) + c{1} & n > x \end{cases}$$
Power (x^n) using Tail-Recursion, O(n)
int power3 (int x, unsigned n, int result = 1) {
if (y == 0)
...
Power (x^n) using Iteration, O(log n)
int power4(int x, unsigned y) {
int result = 1;
while (n > 0) {
if (n % 2)
result *= x;
x *= x;
n /= 2;
} // while
return result;
} // power4
Power (x^n) using Recursion, O(log n)
int power(int x, unsigned n, int result = 1) {
if (n == 0)
return result;
else if (n % 2) // even
return power(x * x, n/2, result * x); // mult, div, mult
else { // odd
return power(x * x, n/2, result); // mult, div
}
}
$$T(n) = \begin{cases} c_0 & n ==0 \ T(n/2) + c_1 & n is even \ T(n/2) + c_2 & n is odd \end{cases}$$
- c2 > c1 due to multiplication, but really c2 = c1 + O(1), so c2 ~ c1
- multiplication is O(1)
We can simplify this into:
$$T(n) = \begin{cases} c_0 & n ==0 \ T(n/2) + c_1 & n > 0 \end{cases}$$
Searching a 2D Sorted Matrix - n x m array
Binary Partition and Stepwise Linear Search are O(n), good