Finding Medians Lecture 09 CS 312 Objectives See
Finding Medians Lecture 09 CS 312
Objectives • See another example of a divide and conquer solution. • See another example of complexity analysis of a divide and conquer algorithm. • See another example of a proof by constructive induction.
Finding the Median • (n log n) is easy. • Can we do better?
Selection problem • Given an array of n elements, find the s -th smallest element. 31415967329 3 rd smallest is 2 6 th smallest is 4 11233456799
Selection and median The selection problem can be used to solve the median problem The median problem can be used to solve the selection problem
Selection Algorithm function selection (T[1. . n], s) i : = 1 ; j : = n repeat p : = median (T[i. . j]) pivotbis (T[i. . j], p, k, l) if s <= k then j : = k else if s >= l then i : = l else return p selection (T, 3): 31415967329 pick p = 3 k l 12133596749 3 <= 3 (s <= k) j : = 3 121
Selection Algorithm function selection (T[1. . n], s) i : = 1 ; j : = n repeat p : = median (T[i. . j]) pivotbis (T[i. . j], p, k, l) if s <= k then j : = k else if s >= l then i : = l else return p There is one problem with this algorithm. What is it?
Still have to find the median • use T[1], as in Quicksort – linear solution to selection on average – O(n 2) in the worst case • approximate the median – still linear on average – but linear in worst-case too
Approximating the median function pseudomed (T[1. . n]) if n<= 5 then return adhocmed(T) z : = floor (n/5) array Z[1. . z] for i : = 1 to z do Z[i] : = adhocmed(T[5 i-4. . 5 i]) return selection (Z, ceil(z/2)) find the median of each 5 -element subarray, find the median of each of those medians. about 3 n/10 elements below and 7 n/10 elements above
Selection Algorithm function selection (T[1. . n], s) i : = 1 ; j : = n repeat p : = pseudomedian (T[i. . j]) pivotbis (T[i. . j], p, k, l) if s <= k then j : = k else if s >= l then i : = l ; else return p glossing over some details, we get. . . t(n) <= dn + t(floor(n/5)) + max{t(m)|m<= ((7 n+12)/10)}
Constructive Induction, again c. n. t(n) <= c n • Why is this a good candidate for constructive induction? For Fall 2002, don’t worry too much about constructive induction here. The basic idea is that we don’t know c, so we just guess and see if the induction goes through.
Constructive Induction, again c. n. (n) <= c n • Why is this a good candidate for constructive induction? – nothing easier works – can induct on n – need a value for c
Setting up the proof Basis case: For any n between 0 and the threshold n 0, show that there exists a c such that t(n) <= cn Inductive step: Assume that t(m) <= cm for any integer m between 1 and n, then constrain c so that t(n) <= cn. The details of this proof are interesting, but not real important for this class.
- Slides: 13