Chap2 - Analysis - Part 2 - Tagged
Chap2 - Analysis - Part 2 - Tagged
Chap2 - Analysis - Part 2 - Tagged
Efficiency Analysis
Chapter 2
Some properties of asymptotic order of growth
f(n) O(f(n))
2
If f1(n) O(g1(n)) and f2(n) O(g2(n)) , then
f1(n) + f2(n) O(max{g1(n), g2(n)})
3
Establishing order of growth using limits
Examples:
• 10n vs. n2
• n(n+1)/2 vs. n2
4
L’Hôpital’s rule and Stirling’s formula
5
Orders of growth of some important functions
All logarithmic functions loga n belong to the same class
(log n) no matter what the logarithm’s base a > 1 is
order log n < order n (>0) < order an < order n! < order nn
6
Basic asymptotic efficiency classes
1 constant
log n logarithmic
n linear
n2 quadratic
n3 cubic
2n exponential
n! factorial
7
Time efficiency of nonrecursive algorithms
General Plan for Analysis
Decide on parameter n indicating input size
8
Useful summation formulas and rules
liu1 = 1+1+ ⋯ +1 = u - l + 1
In particular, liu1 = n - 1 + 1 = n (n)
9
Example 1: Maximum element
10
Example 2: Element uniqueness problem
11
Example 3: Matrix multiplication
Given two n × n matrices A and B, find the time efficiency
of the definition-based algorithm for computing their
product C = AB. By definition, C is an n × n matrix whose
elements are computed as the scalar products of the rows of
matrix A and the columns of matrix B:
12
Example 3: Matrix multiplication
13
Example 4: Counting binary digits
14
Plan for Analysis of Recursive Algorithms
Decide on a parameter indicating an input’s size.
16
Solving the recurrence for M(n)
M(n) = M(n − i) + i
We can use the initial condition. Since it is specified for
n = 0, we have to substitute i = n in the above
equation to get the ultimate result of our backward
substitutions:
M(n) = M(n − n) + n = n.
M(n) = Ɵ(n) 17
Example 2: The Tower of Hanoi Puzzle
18
Example 2: The Tower of Hanoi Puzzle
1 3
19
Pseudocode for Tower of Hanoi
20
Solving recurrence for number of moves
Let us apply the general plan outlined before:
1. The number of disks n is the obvious choice for the input’s
size indicator
2. Moving one disk is the algorithm’s basic operation.
3. If we strictly follow the technique of moving disks as
discussed in the earlier slides worst, best, average cases are
all similar.
4. Clearly, the number of moves M(n) depends on n only, and
we get the following recurrence equation for it:
M(n) = M(n−1) + 1 + M(n−1) for n > 1
With initial condition M(1) = 1.
21
Solving recurrence for number of moves
5. We solve this recurrence by the same method of
backward substitutions
22
Tree of calls for the Tower of Hanoi Puzzle
n
n-1 n-1
1 1 1 1 1 1 1 1
23
Example 3: Counting #bits
24