选出n个元素中第i小的数,i=1:minimum,i = n: maximum,i = ⎣(n+1)/2⎦ or ⎡(n+1)/2⎤: median
很容易想到的一个方法是先排序在索引第i个元素。复杂度:
2. Randomized divide-and conquer algorithm
伪代码
1 2 3 4 5 6 7 8
RAND-SELECT(A,p,q,i) //ith smallest of A[p...q] if p=q then return A[p] r=RAND-PARTITION(A,p,q) k=r-p+1 //k=rank(A[r]) if i=k then return A[r] if i<k then return RAND-SELECT(A,p,r-1,i) else return RAND-SELECT(A,r+1,q,i-k)
Analysis of expected time
划分指示器
再用替换法证明,for constant c>0。 if c is chosen large enough so that cn/4 dominates the Θ(n)
Summary of randomized order-statistic selection
线性期望时间
worst case:
3. Worst-case linear-time order statistics
[Blum, Floyd, Pratt, Rivest, Tarjan]
IDEA: Generate a good pivot recursively.
1 2 3 4 5 6 7 8 9 10
SELECT(i, n) 1. Divide the n elements into groups of 5. Find the median of each 5-element group by rote. 2. Recursively SELECT the median x of the ⎣n/5⎦ group medians to be the pivot. 3. Partition around the pivot x. Let k = rank(x). 4. if i = k then return x elseif i < k then recursively SELECT the ith smallest element in the lower part else recursively SELECT the (i–k)th smallest element in the upper part 3 4步和RAND-SELECT一样
v1.5.2