Lecture 3
Lecture 3
Many algorithms, particularly divide and conquer algorithms, have time complexities which are naturally
modeled by recurrence relations.
A recurrence relation is an equation which is de ned in
terms of itself.
Why are recurrences good things?
1. Many natural functions are easily expressed as recurrences:
an = an;1 + 1 a1 = 1 ;! an = n (polynomial)
an = 2 an;1 a1 = 1
;! an = 2n;1
(exponential)
RecursionInduction!
Mathematical
is
Solving Recurrences
2cbn=2c lg(bn=2c) + n
cn lg(bn=2c) + n dropping oors makes it bigger
= cn(lg n ; (lg 2 = 1)) + n log of division
= cn lg n ; cn + n
cn lg n whenever c > 1
Also known as the iteration method. Plug the recurrence back into itself until you see a pattern.
Example: T (n) = 3T (bn=4c)+ n. Try backsubstituting:
T (n) = n + 3(bn=4c + 3T (bn=16c)
= n + 3bn=4c + 9(bn=16c + 3T(bn=64c))
= n + 3bn=4c + 9bn=16c + 27T (bn=64c)
1
X
n 3 +
i=0
(nlog4 3 T (1))
Recursion Trees
T(n/2)
T(n/2)
T(n/4)
T(n/4)
2
(n/2)
T(n/4)
T(n/4)
(n/4)
2
(n/2)
2
n/2
(n/4)
(n/4)
2
(n/4)
2
n/4
i=0
i=0
(n2)
The Master Theorem: { Let a 1 and b > 1 be constants, let f (n) be a function, and let T (n) be de ned
on the nonnegative integers by the recurrence
T (n) = aT (n=b) + f (n)
where we interpret n=b to mean either bn=bc or dn=be.
Then T (n) can be bounded asymptotically as follows:
1. If f (n) = O(nlogb a; ) for some constant > 0,
then T (n) = O(nlogb a; ).
2. If f (n) = (nlogb a), then T (n) = (nlogb a lg n).
3. If f (n) = (nlogb a+ ) for some constant > 0,
and if af (n=b) cf (n) for some constant c < 1,
and all su ciently large n, then T (n) = (f (n)).
T(n/b)
...
...
f(n)
T(n/b)
f(n/b)
...
...
f(n/b)
13
18
23
18
25
32
23
32
41
Polygon Triangulation
Sorting
The classic divide and conquer recurrence is Mergesort's T (n) = 2T (n=2) + O(n), which divides the data
into equal-sized halves and spends linear time merging
the halves after they are sorted
Since n = O(nlog2 2) = O(n) but not n = O(n1; ),
Case 2 of the Master Theorem applies and T (n) =
O(n log n).
In case 2, the divide and merge steps balance out perfectly, as we usually hope for from a divide-and-conquer
algorithm.
Mergesort Animations
Approaches to Algorithms
Design
Incremental
Job is partly done - do a little more, repeat until done.
A good example of this approach is insertion sort
Divide-and-Conquer
A recursive technique
Divide problem into sub-problems of the same kind.
For subproblems that are really small (trivial), solve
them directly. Else solve them recursively. (conquer)
Combine subproblem solutions to solve the whole
thing (combine)
A good example of this approach is Mergesort.