4 AnalysisOfAlgorithms
4 AnalysisOfAlgorithms
1.4 A NALYSIS OF
‣ introductio
‣ observation
‣ mathematical model
Algorithms F O U R T H E D I T I O N
‣ order-of-growth classi cation
‣ theory of algorithm
R OBERT S EDGEWICK | K EVIN W AYNE
[Link] ‣ memory
n
fi
s
1.4 A NALYSIS OF
‣ introductio
‣ observation
‣ mathematical model
Algorithms
‣ order-of-growth classi cation
‣ theory of algorithm
R OBERT S EDGEWICK | K EVIN W AYNE
[Link] ‣ memory
n
fi
s
Running time
Analytic Engine
3
Cast of characters
Theoretician wants
to understand.
4
fi
e
Predict performance
Provide guarantees
5
.
time
quadratic
64T
32T
16T
linearithmic
8T
linear
size 1K 2K 4K 8K
6
s
N-body simulation
Simulate gravitational interactions among N bodies
Brute force: N 2 steps
Barnes-Hut algorithm: N log N steps, enables new research. Andrew Appel
PU '81
time
quadratic
64T
32T
16T
linearithmic
8T
linear
size 1K 2K 4K 8K
7
.
The challenge
Scienti c method
Observe some feature of the natural world
Hypothesize a model that is consistent with the observations
Predict events using the hypothesis
Verify the predictions by making further observations
Validate by repeating until the hypothesis and observations agree
Principles
Experiments must be reproducible
Hypotheses must be falsi able
fi
.
1.4 A NALYSIS OF
‣ introductio
‣ observation
‣ mathematical model
Algorithms
‣ order-of-growth classi cation
‣ theory of algorithm
R OBERT S EDGEWICK | K EVIN W AYNE
[Link] ‣ memory
n
fi
s
Example: 3-SUM
3-SUM. Given N distinct integers, how many triples sum to exactly zero
30 -40 10 0
30 -40 -20 -10 40 0 10
30 -20 -10 0
1
2
3
int N = [Link]
int count = 0
check each triple
for (int i = 0; i < N; i++)
for simplicity, ignore
for (int j = i+1; j < N; j++
integer over ow
for (int k = j+1; k < N; k++
if (a[i] + a[j] + a[k] == 0
count++
return count
In in = new In(args[0])
int[] a = [Link]() 12
{
fl
;
70
% java ThreeSum [Link]
528
% java ThreeSum [Link]
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
tick tick tick tick tick tick tick tick
4039
In in = new In(args[0])
int[] a = [Link]()
Stopwatch stopwatch = new Stopwatch();
client code
[Link]([Link](a))
double time = [Link]()
[Link]("elapsed time " + time)
} 14
{
Empirical analysis
Run the program for various input sizes and measure running time.
15
Empirical analysis
Run the program for various input sizes and measure running time.
N time (seconds) †
250 0
500 0
1,000 0.1
2,000 0.8
4,000 6.4
8,000 51.1
16,000 ?
16
Data analysis
40 12.8
running time T(N)
6.4
lg(T(N))
30 3.2
1.6
20 .8
.4
10 .2
.1
1K 2K 4K 8K 1
problem size N
Analysis of experimental data (the running time of ThreeSum)
17
analysis
Log-log plot. Plot running time T (N) vs. input size N using log-log scale
log-log plot 51.2 straight line
of slope 3
25.6
.8
T (N) = a N b, where a = 2 c
.4
3 order
of magnitude .2
.1
8K 1K 2K 4K 8K
lg N
ental data (the running time of ThreeSum)
power law
slope
Observations.
N time (seconds) †
8,000 51.1
8,000 51
8,000 51.1
16,000 410.8
validates hypothesis!
19
.
Doubling hypothesis
8,000 51.1 8 3
Doubling hypothesis
N time (seconds) †
8,000 51.1
51.1 = a × 80003
8,000 51
⇒ a = 0.998 × 10 –10
8,000 51.1
fi
?
Experimental algorithmics
determines constant in
System dependent effects
power law
Hardware: CPU, memory, cache,
Software: compiler, interpreter, garbage collector,
System: operating system, network, other apps,
22
.
fi
.
1.4 A NALYSIS OF
‣ introductio
‣ observation
‣ mathematical model
Algorithms
‣ order-of-growth classi cation
‣ theory of algorithm
R OBERT S EDGEWICK | K EVIN W AYNE
[Link] ‣ memory
n
fi
s
Donald Knuth
1974 Turing Award
25
fl
fl
fl
Cost of basic operations
int count = 0
for (int i = 0; i < N; i++
if (a[i] == 0
count++;
N array accesses
operation frequency
variable declaration 2
assignment statement 2
equal to compare N
array access N
increment N to 2 N
27
;
28
Example: Frequency Count - SUM IN A 2D ARRAY
29
Example: Frequency Count - Multiplication IN A 2D ARRAY
30
Example: 2-SUM
int count = 0
for (int i = 0; i < N; i++
for (int j = i+1; j < N; j++
if (a[i] + a[j] == 0)
count++;
1
0 + 1 + 2 + . . . + (N 1) = N (N 1)
2 ⇥
Pf. [ n even] N
=
2
1 2 1
0 + 1 + 2 + . . . + (N 1) = N N
2 2
half of square half of
31
;
1
1 + 2 + 3 + 4 + ... =
12
[Link]
32
fi
Example: 2-SUM
int count = 0
for (int i = 0; i < N; i++
for (int j = i+1; j < N; j++
if (a[i] + a[j] == 0)
count++;
1
0 + 1 + 2 + . . . + (N 1) = N (N 1)
2 ⇥
N
=
2
operation frequency
equal to compare ½ N (N − 1)
tedious to count exactly
array access N (N − 1)
increment ½ N (N − 1) to N (N − 1)
33
;
Cost model. Use some basic operation as a proxy for running time
int count = 0
for (int i = 0; i < N; i++
for (int j = i+1; j < N; j++
if (a[i] + a[j] == 0
count++;
1
0 + 1 + 2 + . . . + (N 1) = N (N 1)
2 ⇥
N
=
2
operation frequency
equal to compare ½ N (N − 1)
Ex 1 ⅙ N 3 + 20 N + 1 ~ ⅙N
166,666,667 N 3/6 ! N 2/2 + N /3
Ex 2 ⅙ N 3 + 100 N 4/3 + 5 ~ ⅙N
Ex 3 ⅙N3 - ½N 2 + ⅓ ~ ⅙N 166,167,000
N 1,000
discard lower-order terms Leading-term approximation
(e.g., N = 1000: 166.67 million vs. 166.17 million)
36
3
.
.
.
fi
fi
.
6
e
N
6
e
increment ½ N (N − 1) to N (N − 1) ~ ½ N 2 to ~ N 2
37
fi
.
Example: 2-SUM
int count = 0
for (int i = 0; i < N; i++
for (int j = i+1; j < N; j++
"inner loop"
if (a[i] + a[j] == 0
count++;
1
0 + 1 + 2 + . . . + (N 1) = N (N 1)
2 ⇥
N
=
2
A. ~ N 2 array accesses.
Bottom line. Use cost model and tilde notation to simplify counts.
38
;
Example: 3-SUM
int count = 0
for (int i = 0; i < N; i++
for (int j = i+1; j < N; j++
for (int k = j+1; k < N; k++ "inner loop"
if (a[i] + a[j] + a[k] == 0
count++;
⇥
N N (N 1)(N 2)
=
3 3!
A. ~ ½ N 3 array accesses. 1 3
⇥ N
6
Bottom line. Use cost model and tilde notation to simplify counts.
39
;
N ⇥ N
1 2
Ex 1. 1 + 2 + … + N. i x dx N
i=1 x=1 2
N N
k k 1
Ex 2. 1k + 2k + … + N k. i x dx N k+1
i=1 x=1 k+1
N ⇥
1 N
1
Ex 3. 1 + 1/2 + 1/3 + … + 1/N. dx = ln N
i=1
i x=1 x
N N N ⇥ ⇥ ⇥
N N N
1 3
Ex 4. 3-sum triple loop. 1 dz dy dx N
i=1 j=i k=j x=1 y=x z=y 6
40
Ex 4. 1 + ½ + ¼ + ⅛ + …
i
1
= 2
i=0
2
x
1 1
dx = 1.4427
x=0 2 ln 2
[Link]
N (N - 1) (N - 2
----------------
6
42
.
In practice
Formulas can be complicated
Advanced mathematics might be required
Exact models best left for experts
TN = c1 A + c2 B + c3 C + c4 D + c5 E
A = array access
B = integer add
frequencie
C = integer compare
(depend on algorithm, input)
D = increment
E = variable assignment
1.4 A NALYSIS OF
‣ introductio
‣ observation
‣ mathematical model
Algorithms
‣ order-of-growth classi cation
‣ theory of algorithm
R OBERT S EDGEWICK | K EVIN W AYNE
[Link] ‣ memory
n
fi
s
De nition. If f (N) ~ c g(N) for some constant c > 0, then the order of growth
of f (N) is g(N)
Ignores leading coef cient
Ignores lower-order terms.
int count = 0
for (int i = 0; i < N; i++
for (int j = i+1; j < N; j++
for (int k = j+1; k < N; k++
if (a[i] + a[j] + a[k] == 0
count++;
fi
.
fi
)
fi
.
time
Common order-of-growth classi cations
200T
log-log plot
512T
exponential
tic
ic
cubi
hm
dra
r
rit
ea
qua
ea
lin
lin
64T
time
8T
4T
2T
logarithmic
T
constant
1K 2K 4K 8K size 512K
order of
name typical code framework description example T(2N) / T(N)
growth
add two
1 constant a = b + c; statement 1
numbers
while (N > 1)
log N logarithmic divide in half binary search ~1
{ N = N / 2; ... }
divid
N log N linearithmic [see mergesort lecture] mergesort ~2
and conquer
47
fi
e
fi
Example 1: Common order-of-growth classi cations
order of
name typical code framework description example T(2N) / T(N)
growth
add two
1 constant a = b + c; statement 1
numbers
while (N > 1)
log N logarithmic divide in half binary search ~1
{ N = N / 2; ... }
divid
N log N linearithmic [see mergesort lecture] mergesort ~2
and conquer
48
fi
e
fi
Example 1: Common order-of-growth classi cations
Time: f(n) = 2n + 3
Space: f(n) = n + 3
49
fi
Example 2: Common order-of-growth classi cations
1
n+1
Time: f(n) = 2n + 2
Space: f(n) = n + 2
50
fi
Example 3: Common order-of-growth classi cations
n+1
n/2
51
fi
Example 4: Common order-of-growth classi cations
n+1
n x (n+1)
n xn
Time: f(n) = n2
52
fi
Example 5: Common order-of-growth classi cations
i j No. Of times
0 0 0
1 0,1 1
2 0,1,2 2
3 0,1,2,3 3
53
fi
Example 6: Common order-of-growth classi cations
i p
1 0+1
2 1+2
3 1+2+3
4 1+2+3+4
- -
- -
k 1+2+3+4+…
k(k+1)/2 >
k2 >
1/2
k > (n)
54
n
fi
Example 7: Common order-of-growth classi cations
55
fi
Example 8: Common order-of-growth classi cations
56
fi
Example 9: Common order-of-growth classi cations
57
fi
Example 10: Common order-of-growth classi cations
58
fi
Example 12: Common order-of-growth classi cations
59
fi
Example 13: Common order-of-growth classi cations
60
fi
Example 14: Common order-of-growth classi cations
61
fi
Example 15: Common order-of-growth classi cations
62
fi
Example 16: Common order-of-growth classi cations
63
fi
Example 17: Common order-of-growth classi cations
64
fi
Example 18: Common order-of-growth classi cations
65
fi
Example 20: Common order-of-growth classi cations
66
fi
Example 21: Common order-of-growth classi cations 2-SUM
int count = 0
for (int i = 0; i < N; i++
for (int j = i+1; j < N; j++
if (a[i] + a[j] == 0
count++;
67
;
fi
Binary search demo
Goal. Given a sorted array and a key, nd index of the key in the array
6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
lo hi
68
.
fi
.
Binary
Trivialsearch: Java implementation
to implement
First binary search published in 1946
First bug-free one in 1962
Bug in Java's [Link]() discovered in 2006.
int lo = 0, hi = [Link]-1
while (lo <= hi
return -1
}
Invariant. If key appears in the array a[], then a[lo] ≤ key ≤ a[hi].
69
{
T (N) ≤ T (N / 2) + 1 [ given ]
= 1 + lg N
70
fl
f
fi
fi
e
Algorithm. inpu
30 -40 -20 -10 40 0 10 5
Step 1: Sort the N (distinct) numbers
Step 2: For each pair of numbers a[i] sor
and a[j], binary search for -(a[i] + a[j]) -40 -20 -10 0 5 10 30 40
binary searc
(-40, -20) 60
Analysis. Order of growth is N 2 log N.
(-40, -10) 50
Step 1: N 2 with insertion sort (-40, 0) 4
Step 2: N 2 log N with binary search (-40, 5) 35
(-40, 10) 3
⋮ ⋮
Remark. Can achieve N 2 by modifying (-20, -10) 3
binary search step. ⋮ ⋮ only count i
a[i] < a[j] < a[k
(-10, 0) 1
to avoi
⋮ ⋮ double counting
( 10, 30) -4
71
( 10, 40) -50
t
Comparing programs
Hypothesis. The sorting-based N 2 log N algorithm for 3-SUM is signi cantly faster in
practice than the brute-force N 3 algorithm
32,000 14.88
64,000 59.16
[Link]
fi
1.4 A NALYSIS OF
‣ introductio
‣ observation
‣ mathematical model
Algorithms
‣ order-of-growth classi cation
‣ theory of algorithm
R OBERT S EDGEWICK | K EVIN W AYNE
[Link] ‣ memory
n
fi
s
Types of analyses
74
fi
.
Theory of algorithms
Goals
Establish “dif culty” of a problem
Develop “optimal” algorithms.
Approach.
Suppress details in analysis: analyze “to within a constant factor.
Eliminate variability in input model: focus on the worst case
75
.
fi
.
½ N2
asymptotic 10 N 2 classif
Big Theta Θ(N2)
order of growth 5 N 2 + 22 N log N + 3 algorithms
⋮
10 N 2
100 N develo
Big Oh Θ(N2) and smaller O(N2)
22 N log N + 3 N upper bounds
⋮
½N2
N5 develo
Big Omega Θ(N2) and larger Ω(N2)
N 3 + 22 N log N + 3 N lower bounds
⋮
y
Goals
Establish “dif culty” of a problem and develop “optimal” algorithms
Ex. 1-SUM = “Is there a 0 in the array? ”
Optimal algorithm.
Lower bound equals upper bound (to within a constant factor)
Ex. Brute-force algorithm for 1-SUM is optimal: its running time is Θ(N).
77
.
fi
fi
.
Goals
Establish “dif culty” of a problem and develop “optimal” algorithms
Ex. 3-SUM.
78
.
fi
fi
.
Goals
Establish “dif culty” of a problem and develop “optimal” algorithms
Ex. 3-SUM.
Open problems.
Optimal algorithm for 3-SUM
Subquadratic algorithm for 3-SUM
Quadratic lower bound for 3-SUM?
79
.
fi
fi
?
Start
Develop an algorithm
Prove a lower bound.
Gap?
Lower the upper bound (discover a new algorithm)
Raise the lower bound (more dif cult).
Caveats.
Overly pessimistic to focus on worst case
Need better than “to within a constant factor” to predict performance.
80
.
fi
?
10 N 2
provid
Tilde leading term ~ 10 N2 10 N 2+ 22 N log N
approximate model
10 N 2+ 2 N + 37
½ N2
asymptotic classif
Big Theta Θ(N2) 10 N 2
order of growth algorithms
5N 2+ 22 N log N + 3N
10 N 2
develo
Big Oh Θ(N2) and smaller O(N2) 100 N
upper bounds
22 N log N + 3 N
½N2
develo
Big Omega Θ(N2) and larger Ω(N2) N 5
lower bounds
N 3 + 22 N log N + 3 N
1.4 A NALYSIS OF
‣ introductio
‣ observation
‣ mathematical model
Algorithms
‣ order-of-growth classi cation
‣ theory of algorithm
R OBERT S EDGEWICK | K EVIN W AYNE
[Link] ‣ memory
n
fi
s
Basics
Byte. 8 bits
Megabyte (MB). 1 million or 220 bytes
Gigabyte (GB). 1 billion or 230 bytes
83
.
boolean 1 char[] 2 N + 24
byte 1 int[] 4 N + 24
char 2 double[] 8 N + 24
oat 4
long 8
type bytes
double 8
char[][] ~2MN
primitive types
int[][] ~4MN
double[][] ~8MN
two-dimensional arrays
84
fl
Typical memory usage for objects in Java
32 bytes
86
t
Example
16 byte
public class WeightedQuickUnionU
(object overhead)
8N + 88 bytes
public WeightedQuickUnionUF(int N
id = new int[N]
sz = new int[N]
for (int i = 0; i < N; i++) id[i] = i
for (int i = 0; i < N; i++) sz[i] = 1;
A. 8 N + 88 ~ 8 N bytes.
87
{
Empirical analysis
Execute program to perform experiments
Assume power law and formulate a hypothesis for running time
Model enables us to make predictions
Mathematical analysis
Analyze algorithm to count frequency of operations
Use tilde notation to simplify analysis
Model enables us to explain behavior
Scienti c method
Mathematical model is independent of a particular system;
applies to machines not yet built
Empirical analysis is necessary to validate mathematical models
and to make predictions.
88
fi
.