Professional Documents
Culture Documents
A[q] A[q]
p q r
Randomized Selection
Select(A, p, r, i)
if (p == r) then return A[p];
q = Partition(A, p, r)
k = q - p + 1;
if (i == k) then return A[q];
if (i < k) then
return Select(A, p, q-1, i);
else
return Select(A, q+1, r, i-k);
A[q] A[q]
p q r
:Example
Select the 7th smallest element :
Partition:
i=3
7
Analysis
T(n) = T(max(k,n-k-1)) + Θ(n)
The worst-case running time:
T(n) = T(n –1) + Θ(n) = Θ(n2)
If the partition was perfect (q = n/2) we have:
T(n) = T(n/2) + Θ(n) = Θ(n)
Summary
Works fast: linear expected time.
Excellent algorithm in practice.
But, the worst case is very bad: Θ(n2).
Worst-Case Linear-Time Selection
Procedure select (A, low…high, k)
1. If n is small, for example n<6, then, sort and return the kth smallest
element .(bounded by 7 steps)
2. If n>5, partition the numbers into groups of 5. (time n/5)
3. Sort the elements in each group. Select the middle elements
(medians). (time- 7n/5)
4. Select the median of the medians mm
5. Partition the elements into 3 lists (L,R,M) according to mm.
1. L A[i] < mm
2. R A[i]> mm
3. M A[i] = mm
.Note that the rank of mm is r=|L|+1 (|L| is the size of L)
6. case:
k=r return mm
k<r return k th smallest of set L. select (A, 1..|L|, k)
k>r return k-r th smallest of set R. select (A, r+1..|R|, k-r th )
Example
L = {8, 17, 11, 25, 14, 3, 2, 13, 12, 6, 5, 16, 22, 23, 7}
We repeat the same procedure above: select (L, 1,|L|, k)
So we set A = L.
We divide the elements into 3 groups of 5 elements each:
(8,17,11,25,14), (3,2,13,12,6), (5,16,22,23,7).
Sort each of the group, and find the new set of medians: M = {14, 6,
16}.
the new median of medians mm is 14.
Next, partition A into three sequences: