CSE 326: Data Structures Lecture #3 Analysis of Recursive Algorithms
CSE 326: Data Structures Lecture #3 Analysis of Recursive Algorithms
Lecture #3
Analysis of Recursive
Algorithms
Alon Halevy
Fall Quarter 2000
i 1
j i
i 1
i 1
1 (n i 1) (n 1) i
n(n 1) n(n 1)
n(n 1)
n2
2
2
Recursion
A recursive procedure can often be analyzed
by solving a recursive equation
Basic form:
T(n) = if (base case) then some constant
else ( time to solve subproblems +
time to combine solutions )
Equation:
T(0) b
T(n) c + T(n 1)
for n>0
Sum, Continued
Equation:
T(0) b
T(n) c + T(n 1)
Solution:
T(n)
c + c + T(n-2)
c + c + c + T(n-3)
kc + T(n-k) for all k
nc + T(0) for k=n
cn + b = O(n)
for n>0
12 30 35 75 83 87 90 97 99
for n>1
Example: MergeSort
Split array in half, sort each half, merge together
2 subproblems, each half as large
linear amount of work to combine
T(1) b
T(n) 2T(n/2) + cn
for n>1
T(n) 2T(n/2)+cn
2(2(T(n/4)+cn/2)+cn
4(2(T(n/8)+c(n/4))+cn+cn
= 8T(n/8)+cn+cn+cn
2kT(1) + cn log n
where k = log n
= O(n log n)
2kT(n/2k)+kcn
Why?
if n > 1
Analysis
let be (1 + 5)/2 which satisfies 2 = + 1
show by induction on n that T(n) >= b n - 1
T(n)
T(n - 1) + T(n - 2) + c
b n-2 + b n-3 + c
b n-3( + 1) + c
b n-3 2 + c
b n-1
- 1
for all
0
0
2
1
1
0
Memoization
a form of dynamic programming
Kinds of Analysis
So far we have considered worst case analysis
We may want to know how an algorithm performs
on average
Several distinct senses of on average
amortized
average time per operation over a sequence of operations
average case
average time over a random distribution of inputs
expected case
average time for a randomized algorithm over different random
seeds for any input
Amortized Analysis
Consider any sequence of operations applied to a
data structure
your worst enemy could choose the sequence!
Stack ADT
A
Stack operations
push
pop
is_empty
EDCBA
B
C
D
E
F
Push(e){
if (top == maxsize){
temp = new int[2*maxsize];
copy data into temp;
deallocate data;
data = temp; }
else { data[++top] = e; }
log n
lets say a regular push takes time a, and stretching an array contain k elements
takes time kb, for some constants a and b.
log n
an b(1 2 4 8 ... n) an b 2i
i o
Wrapup