| title |
|---|
Analyzing Recursive Algorithms |
- Choose your parameter
$n$ (input size) - Identify the [basic operation]{.underline}.
- Check if work varies by input.
- If it doesn't vary, we only analyze once.
- If it varies, we have to analyze bext/worst/average separately.
- Set up [recurrence relation]{.underline}
- Express how much work algorithm does in terms of smaller problems.
- Solve the recurrence (or, at the very least, establish its solution's order of growth) by [backward substitution]{.underline} or another method.
More on Step 4:
$$ \text{Format: } T(n) = \text{[work for recursive calls] + [work done at current level]} $$ Also, don't forget to define the initial condition.
Q: Find the order of growth of this recursive function.
ALGORITHM F(n)
// Computes n! recursively
// Input: A nonnegative integer n
// Output: The value of n!
if n = 0 return 1
else return F(n-1) * n
Definition:
A:
Step 1: Parameter
Step 2: Basic operation is multiplication.
Step 3: Work is same for all inputs of size
Step 4: Set up recurrence:
We want to count number of basic operatios, so we can express this as:
$M(n-1)$ multiplications are spent computing$F(n-1)$ - One more multiplication is needed to multiply the result by
$n$ (hence$+1$ )
Step 5: Solve recurrence
Now, we can do backwards substitution (solve
Thus:
Thus, the time efficiency of this algorithm is
Tower of Hanoi: Move
- Only 1 disk can be moved at a time, and a larger disk cannot be placed on top of a smaller one.
- Initially, all disks are on peg A in order of size (largest on bottom)
Recursive Strategy:
- Move top
$n-1$ disks from A to B (using C as auxiliary) - Move the largest disk from A to C
- Move n-1 disks from B to C (using A as auxiliary)
Q: You know the drill.
A:
Step 1.
Step 2. Basic operation: Moving on disk
Step 3.
Step 4. Set up recurrence:
Step 5. Backwards substitution
When
Thus, time complexity is
Recurrence:
This creates a tree of recursive calls with massive overlap.
F(5) calls F(4) and F(3)
F(4) calls F(3) and F(2)
F(3) calls F(2) and F(1)
et cetera
There isn't a simple closed form to solve for, so this one is currently out of our reach.
- We'll cover this again in a later chapter, this was just to illustrate the limits of this general approach.