SLIDE 11 11
Quadratic Time: O(n2)
- Quadratic time. Enumerate all pairs of elements.
- Closest pair of points. Given a list of n points in the plane (x1, y1),
…, (xn, yn), find the pair that is closest.
- O(n2) solution. Try all pairs of points.
- Remark. Ω(n2) seems inevitable, but this is just an illusion.
min ← (x1 - x2)2 + (y1 - y2)2 for i = 1 to n { for j = i+1 to n { d ← (xi - xj)2 + (yi - yj)2 if (d < min) min ← d } }
don't need to take square roots see chapter 5
Cubic Time: O(n3)
- Cubic time. Enumerate all triples of elements.
- Set disjointness. Given n sets S1, …, Sn each of which is a subset of
1, 2, …, n, is there some pair of these which are disjoint?
- 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 } }
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?
- O(nk) solution. Enumerate all subsets of k nodes.
– Check whether S is an independent set = O(k2). – Number of k element subsets = – O(k2 nk / k!) = O(nk). foreach subset S of k nodes { check whether S in an independent set if (S is an independent set) report S is an independent set } }
n k ⎛ ⎝ ⎜ ⎞ ⎠ ⎟ = n (n−1) (n− 2) L (n− k +1) k (k −1) (k − 2) L (2) (1) ≤ nk k!
poly-time for k=17, but not practical k is a constant