Order Statistics
Randomized algorithm for finding the ith element
- Divide and conquer approach
- Main idea:
PARTITION
int RANDOMIZED_SELECT(int A[],int p,int r,int i)
{
if(p==r) return A[p];
int q=RANDOMIZED_PARTION(A,p,r);
int k=q-p+1;
if(i==k)
return A[q];
if(i<k)
return RANDOMIZED_SELECT(A,p,q-1,i);
else
return RANDOMIZED_SELECT(A,q+1,r,i-k);
}
Example
int main()
{
int A[]={6,10,13,5,8,3,2,11};
cout<<RANDOMIZED_SELECT(A,0,7,7);
}
运行结果:
11
Analysis
- What is the worst-case running time?
Unlucky:
即子问题分别包含n-1个元素和0个元素。
和之前快排的时间复杂度分析少了一项T(n/10)
,因为该问题的求解只需要解决其中一个子问题即可,而快排是所有的子问题都需要执行。
Summary of randomized order-statistics selection - Works fast: linear expected time
- Excellent algorithm in practice
- But, the worst case is very bad:
Θ(n^2)
IDEA: Generate a good pivot recursively.(递归地生成一个好的主元。)
Pictorial Analysis of Select(图解分析)
将所有元素划分为组,每组5个元素,然后按组排序,找到中位数,再找到中位数的中位数。
最坏情况为线性时间的选择算法
通过执行下列步骤,算法SELECT可以确定一个有n>1个不同元素的输入数组中的第i小的元素。(若n=1,则返回唯一输入数值)
Selection Analysis