The Master Theorem
When doing various sorting algorithms in class, we talked a little about the order of an algorithm. Some of these analyses were straightforward, such as selection sort and insertion sort. But other sorting algorithms such as merge sort and quicksort are harder to analyze due to their recursive structure. When analyzing the runtime of recursive functions, we are often faces with a recursive identity that we need to solve. The master theorem provides a solution to many of these recurrences.
Lets say the following is our function:
def T(n):
if n>1:
f(n) operations done here
T(n/b)
T(n/b)
..... called a times .....
T(n/b)
T(n/b)
The recurrence formula for this method will be: (a & b constants, a >= 1, b > 1)
T(n) = aT(n/b) + f(n)
Now the master theorem says that:
- If
where
, then
- If
where
then
- If
where
then
Example:
- T(n) = 9T(n/3) + n:
- a = 9
- b = 3
- f(n) = n
- Since f(n) = O(n^(log{9}{3} - 1), it is case 1
- Hence, T(n) = 0(n^(log{9}{3})) = 0(n^2)
1) Introduction to Algorithms, 3rd edition, MIT Press
After this post, I felt a feeling of enlightenment.
ReplyDeleteIt made me chuckle.