02b Analysis
02b Analysis
Polynomial-Time
Desirable scaling property. When the input size doubles, the algorithm
should only slow down by some constant factor C.
1
Worst-Case Analysis
Worst case running time. Obtain bound on largest possible running time
of algorithm on input of a given size N.
Generally captures efficiency in practice.
Draconian view, but hard to find effective alternative.
2
Worst-Case Polynomial-Time
Exceptions.
Some poly-time algorithms do have high constants and/or
exponents, and are useless in practice.
Some exponential-time (or worse) algorithms are widely used
because the worst-case instances seem to be rare.
simplex method
Unix grep
3
Why It Matters
10^25≌ 10 septillion !
4
Asymptotic Order of Growth
A prelude: some functions we use
6
Asymptotic Order of Growth
Upper bounds. T(n) is O(f(n)) if there exist constants c > 0 and integer
n0 ³ 0 such that for all n ³ n0 we have T(n) £ c · f(n).
7
Notation
8
Properties
Transitivity.
If f = O(g) and g = O(h) then f = O(h).
If f = W(g) and g = W(h) then f = W(h).
If f = Q(g) and g = Q(h) then f = Q(h).
Additivity.
If f = O(h) and g = O(h) then f + g = O(h).
If f = W(h) and g = W(h) then f + g = W(h).
If f = Q(h) and g = Q(h) then f + g = Q(h).
Is it true that if f = O(h) then 2f = O(2h)?
No, check f(n) = 2n, h(n) = n.
9
Useful sufficient conditions
10
Asymptotic Bounds for Some Common Functions
11
A Survey of Common Running Times
Linear Time: O(n)
Linear time. Running time is at most a constant factor times the size
of the input.
max ¬ a1
for i = 2 to n {
if (ai > max)
max ¬ ai
}
13
Linear Time: O(n)
i = 1, j = 1
while (both lists are nonempty) {
if (ai £ bj) append ai to output list and increment i
else(ai £ bj)append bj to output list and increment j
}
append remainder of nonempty list to output list
14
O(n log n) Time
O(n log n) solution. Sort the time-stamps. Scan the sorted list in
order, identifying the maximum gap between successive time-stamps.
15
Quadratic Time: O(n2)
Closest pair of points. Given a list of n points in the plane (x1, y1), …,
(xn, yn), find the pair that is closest.
min ¬ d
}
}
Remark. W(n2) seems inevitable, but this is just an illusion. see chapter 5
16
Cubic Time: O(n3)
O(n3) solution. For each pairs of sets, determine if they are disjoint.
foreach set Si {
foreach other set Sj {
foreach element p of Si {
determine whether p also belongs to Sj
}
if (no element of Si belongs to Sj)
report that Si and Sj are disjoint
}
}
17
Polynomial Time: O(nk) Time
Independent set of size k. Given a graph, are there k nodes such that
no two are joined by an edge?
k is a constant
18
Exponential Time
S* ¬ f
foreach subset S of nodes {
check whether S in an independent set
if (S is largest independent set seen so far)
update S* ¬ S
}
}
19