0%

Lec06 顺序统计、中值

MIT算法导论课程:Lec06 顺序统计、中值,对应书上的章节:Chapter 9

1. Order statistics

选出n个元素中第i小的数,i=1:minimumi = n: maximumi = ⎣(n+1)/2⎦ or ⎡(n+1)/2⎤: median

很容易想到的一个方法是先排序在索引第i个元素。复杂度:Θ(nlgn)

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

划分指示器

Xk={1 if PARTITION generates a k:nk1 split, 0 otherwise. 

T(n)={T(max{0,n1})+Θ(n) if 0:n1 split, T(max{1,n2})+Θ(n) if 1:n2 split, T(max{n1,0})+Θ(n) if n1:0 split =k=0n1Xk(T(max{k,nk1})+Θ(n))

再用替换法证明,E[T(n)]cnfor constant c>0。 E[T(n)]2nk=n/2n1ck+Θ(n)2c(38n2)+Θ(n)n=cn(cn4Θ(n))cn if c is chosen large enough so that cn/4 dominates the Θ(n)

Summary of randomized order-statistic selection

  • 线性期望时间
  • worst case:Θ(n2)

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一样

Analysis

  • 实际上,此算法运行缓慢,因为n前面的常数很大
  • 随机算法更加实用。

练习:为什么不分成3组?

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

欢迎关注我的其它发布渠道

Powered By Valine
v1.5.2