02 Algorithm Analysis
02 Algorithm Analysis
A LGORITHM A NALYSIS
‣ computational tractability
‣ asymptotic order of growth
‣ implementing Gale–Shapley
‣ survey of common running times
‣ computational tractability
‣ asymptotic order of growth
‣ implementing Gale–Shapley
‣ survey of common running times
SECTION 2.1
A strikingly modern thought
Analytic Engine
3
Models of computation: Turing machines
4
Models of computation: word RAM
assume w ≥ log2 n
Word RAM.
・Each memory location and input/output cell stores a w-bit integer.
・Primitive operations: arithmetic/logic operations, read/write memory,
array indexing, following a pointer, conditional branch, …
program a[i] i
.
.
.
output …
Caveat. At times, need more refined model (e.g., multiplying n-bit integers). 5
Brute force
Ex. Stable matching problem: test all n! perfect matchings for stability. 6
Polynomial running time
Desirable scaling property. When the input size doubles, the algorithm
should slow down by at most some multiplicative constant factor C.
7
Polynomial running time
Abstract
AbstractChen, Grigni, and Papadimitriou (WADS’97 and STOC’98)
have introduced a modified notion of planarity, where two
Chen, Grigni, and Papadimitriou (WADS’97 and STOC’98)
faces are considered adjacent if they share at least one point.
have introduced a modified notion of planarity, where two
The corresponding abstract graphs are called map graphs.
faces are considered adjacent if they share at least one point.
Chen [Link]. raised the question of whether map graphs can be
The corresponding abstract graphs are called map graphs.
recognized in polynomial time. They showed that the decision Figure 1. Large
Chen [Link]. raised the question of whether map graphs can be
9
Other types of analyses
‣ computational tractability
‣ asymptotic order of growth
‣ implementing Gale–Shapley
‣ survey of common running times
SECTION 2.2
Big O notation
12
Analysis of algorithms: quiz 1
Let f(n) = 3n2 + 17 n log2 n + 1000. Which of the following are true?
D. Neither A nor B.
13
Big O notational abuses
14
Big O notation: properties
Reflexivity. f is O( f).
16
Analysis of algorithms: quiz 2
B. f(n) is Ω(g(n)) iff there exists a constant c > 0 such that f(n) ≥ c · g(n) ≥ 0
for infinitely many n.
D. Neither A nor B.
17
Analysis of algorithms: quiz 2
B. f(n) is Ω(g(n)) iff there exist constants c > 0 such that f(n) ≥ c · g(n) ≥ 0
for infinitely many n.
why not use this definition instead?
c1 = 1 / c2
18
Big Theta notation
Tight bounds. f(n) is Θ(g(n)) if there exist constants c1 > 0, c2 > 0, and n0 ≥ 0
such that 0 ≤ c1 · g(n) ≤ f(n) ≤ c2 · g(n) for all n ≥ n0. c2 · g(n)
f(n)
Ex. f(n) = 32n2 + 17n + 1. c1 · g(n)
・f(n) is Θ(n2). choose c = 32, c = 50, n = 1
1 2 0
between ½ n log2 n
and n log2 n
19
Analysis of algorithms: quiz 3
f (n)
B. f(n) is Θ(g(n)) iff nlim for0 some constant 0 < c < ∞.
= c >
g(n)
2n n
f (n) =
3n n
g(n) = n
20
Asymptotic bounds and limits
f (n)
Proposition. If nlim for0 some constant 0 < c < ∞ then f(n) is Θ(g(n)).
= c >
g(n)
Pf.
・By definition of the limit, for any ε > 0, there exists n0 such that
f (n)
c c+
<latexit sha1_base64="4471u2rVjPFvRKTehhYE1ZF2UoY=">AAACbnicbVDRSiMxFE1HV7vdVas+7IOIYYtQEctUBJV9EZaFfXRhq0KnlMztnRrMJENyR1qGfpFf4+PqV/gHm6lFtnVvSHI4597c3BNnSjoKwz+VYGn5w8pq9WPt0+e19Y365taVM7kF7IBRxt7EwqGSGjskSeFNZlGkscLr+O57qV/fo3XS6N80zrCXiqGWiQRBnurXf3DgRzzCzEllNI+++aWwvHiUWAFF0tQHk2JYnnMq8MO3slq/3ghb4TT4e9CegQabxWV/s7IVDQzkKWoCJZzrtsOMeoWwJEHhpBblDjMBd2KIXQ+1SNH1ium8E77vmQFPjPVbE5+y/1YUInVunMY+MxV06xa1kvyf1s0pOesVUmc5oYbXRkmuOBlemscH0iKQGnsgwEr/Vw63wttE3uK5LtO3M4S5SYpRriWYAS6wikZkxcS72F707D3oHLfOW+Gvk8bF2czOKtthX1mTtdkpu2A/2SXrMGAP7JE9sefKS/Al2A32XlODyqxmm81F0PwL9Tm8EA==</latexit>
g(n)
f (n)
Proposition. If lim = 0 , then f(n) is O(g(n)) but not Ω(g(n)).
n g(n)
<latexit sha1_base64="a6Ox4O/LCYsW5EpcWyBdjU0iDhE=">AAACZHicbVDLSgMxFE3HV62vqrgSJFgE3ZSpCFZEKLhxqWBV6JSSSe+0wUwyJHfUMszH+DVudekX+Btmahe2eiCXw7mv3BMmUlj0/c+SNze/sLhUXq6srK6tb1Q3t+6sTg2HNtdSm4eQWZBCQRsFSnhIDLA4lHAfPl4W+fsnMFZodYujBLoxGygRCc7QSb3qeSBF3MsUDYwYDJEZo59pIFSEo5wG5zSIDONZdKiO8mxQxEK8KIJf6VVrft0fg/4ljQmpkQmue5ulraCveRqDQi6ZtZ2Gn2A3YwYFl5BXgtRCwvgjG0DHUcVisN1sfGVOD5zSp5E27imkY/V3R8Zia0dx6CpjhkM7myvE/3KdFKNmNxMqSREU/1kUpZKipoVltC8McJQjRxg3wv2V8iFzvqAzdmrLeHYCfOqS7CVVgus+zKgSX9Cw3LnYmPXsL2kf18/q/s1JrdWc2Fkmu2SfHJIGOSUtckWuSZtw8kreyDv5KH15a962t/NT6pUmPdtkCt7eNxcjuXA=</latexit>
f (n)
Proposition. If lim = , then f(n) is Ω(g(n)) but not O(g(n)).
n g(n) <latexit sha1_base64="7KIVqEi//Gxt4Gr531t4InKKrao=">AAACaXicbVDRatswFFW8dk2zdkuzl7K+iIZB+xKcMVhHGQT20scU5iUQhyAr14moLBnpumsw/p1+TV9b6D/0Iyq7fmjSHZA4nHOvru6JUiks+v5jw3u3tf1+p7nb+rC3//FT+6Dz1+rMcAi4ltqMI2ZBCgUBCpQwTg2wJJIwiq5+l/7oGowVWv3BVQrThC2UiAVn6KRZexBKkcxyRUMjFktkxuh/NBQqxlVBw3MaxobxPD5Rp0W+KO9S/FU5VVFr1u76Pb8CfUv6NemSGsPZQaMTzjXPElDIJbN20vdTnObMoOASilaYWUgZv2ILmDiqWAJ2mlerFvSrU+Y01sYdhbRSX3fkLLF2lUSuMmG4tJteKf7Pm2QYn01zodIMQfGXQXEmKWpa5kbnwgBHuXKEcSPcXylfMhcOunTXplRvp8DXNslvMiW4nsOGKvEGDStciv3NzN6S4FvvZ8+//N4dnNVxNskROSYnpE9+kAG5IEMSEE5uyR25Jw+NJ6/jHXpfXkq9Rt3zmazB6z4DXwy7+A==</latexit>
21
Asymptotic bounds for some common functions
Logarithms and polynomials. loga n is O(n d ) for every a > 1 and every d > 0.
Pf. loga n
lim d
= 0
n n
Exponentials and polynomials. n d is O(r n ) for every r > 1 and every d > 0.
Pf. nd
lim n = 0
n r
23
2. A LGORITHM A NALYSIS
‣ computational tractability
‣ asymptotic order of growth
‣ implementing Gale–Shapley
‣ survey of common running times
SECTION 2.3
Efficient implementation
25
Efficient implementation
26
Data representation: making a proposal
next proposal to
hospital h 3 4 1 5 2 null
pref[]
1st 2nd 3rd 4th 5th 6th 7th 8th
1 2 3 4 5 6 7 8
rank[]
4th 8th 2nd 5th 6th 7th 3rd 1st
for i = 1 to n
rank[pref[i]] = i
Bottom line. After Θ(n2) preprocessing time (to create the n ranking arrays),
it takes O(1) time to accept/reject a proposal. 28
Stable matching: summary
Theorem. In the worst case, any algorithm to find a stable matching must
query the hospital’s preference list Ω(n2) times.
29
2. A LGORITHM A NALYSIS
‣ computational tractability
‣ asymptotic order of growth
‣ implementing Gale–Shapley
‣ survey of common running times
SECTION 2.4
Constant time
bounded by a constant,
Examples. which does not depend on input size n
・Conditional branch.
・Arithmetic/logic operation.
・Declare/initialize a variable.
・Follow a link in a linked list.
・Access element i in an array.
・Compare/exchange two elements in an array.
・…
31
Linear time
Merge two sorted lists. Combine two sorted linked lists A = a1, a2, …, an and
B = b1, b2, …, bn into a sorted whole.
i ← 1; j ← 1.
WHILE (both lists are nonempty)
IF (ai ≤ bj) append ai to output list and increment i.
ELSE append bj to output list and increment j.
Append remaining elements from nonempty list to output list.
32
TARGET SUM
input
−20 10 20 30 35 40 60 70 T = 60
(sorted)
i j
33
TARGET SUM
input
−20 10 20 30 35 40 60 70 T = 60
(sorted)
i j
34
Logarithmic time
remaining elements
O(log n) algorithm. Binary search.
・Invariant: If x is in the array, then x is in A[lo .. hi].
・After k iterations of WHILE loop, (hi − lo + 1) ≤ n / 2k k ≤ 1 + log2 n.
lo ← 1; hi ← n.
WHILE (lo ≤ hi)
mid ← ⎣(lo + hi) / 2⎦.
IF (x < A[mid]) hi ← mid − 1.
ELSE IF (x > A[mid]) lo ← mid + 1.
ELSE RETURN mid.
RETURN −1.
35
Logarithmic time
O(log n)
[Link]
36
SEARCH IN A SORTED ROTATED ARRAY
90
35
50
85
80
60
65
75 67
80 85 90 95 20 30 35 50 60 65 67 75
1 2 3 4 5 6 7 8 9 10 11 12
37
SEARCH IN A SORTED ROTATED ARRAY
O(log n) algorithm.
・Find index k of smallest element.
・Binary search for x in either A[1 .. k−1] or A[k .. n].
find index of smallest element
lo ← 1; hi ← n.
IF (A[lo] ≤ A[hi]) RETURN 0 sorted
40
LARGEST EMPTY INTERVAL
41
Quadratic time
Closest pair of points. Given a list of n points in the plane (x1, y1), …, (xn, yn),
find the pair that is closest to each other.
min ← ∞.
FOR i = 1 TO n
FOR j = i + 1 TO n
d ← (xi − xj)2 + (yi − yj)2.
IF (d < min)
min ← d.
Remark. Ω(n2) seems inevitable, but this is just an illusion. [see §5.4]
42
Cubic time
FOR i = 1 TO n
FOR j = i + 1 TO n
FOR k = j + 1 TO n
IF (ai + aj + ak = 0)
RETURN (ai, aj, ak).
Remark. Ω(n3) seems inevitable, but O(n2) is not hard. [see next slide]
43
3-SUM
O(n2) algorithm.
44
3-SUM
O(n2) algorithm.
・Sort the array a.
・For each integer ai : solve TARGET-SUM on the array containing all
elements except ai with the target sum T = −ai.
45
Polynomial time
Independent set of size k. Given a graph, find k nodes such that no two
are joined by an edge.
k is a constant
k
Exponential time. Running time is O(2n ) for some constant k > 0.
S* ← ∅.
FOREACH subset S of n nodes:
Check whether S is an independent set.
IF (S is an independent set and ⎢S⎟ > ⎢S*⎟)
S* ← S. independent set of max size
RETURN S*.
47
Exponential time
k
Exponential time. Running time is O(2n ) for some constant k > 0.
Euclidean TSP. Given n points in the plane, find a tour of minimum length.
π* ← ∅.
FOREACH permutation π of n points:
Compute length of tour corresponding to π.
IF (length(π) < length(π*))
π* ← π.
for simplicity, we’ll assume Euclidean
RETURN π*. distances are rounded to nearest integer
(to avoid issues with infinite precision)
48
Analysis of algorithms: quiz 4
B. O(2cn ) for some constant c > 0. includes 3n but doesn’t include n! = 2Θ(n log n)
D. Neither A nor B.
49