median of medians(中位数的中位数)

BFPRT(Blum、Floyd、Pratt、Rivest、Tarjan)算法

https://en.wikipedia.org/wiki/Median_of_medians

最坏时间复杂度为O(n):

T(n)T(n5)+T(7n10)+anT(n)cnT(n5)+T(7n10)+ancn5+7cn10+an=9cn10+ancnc10a

void insertionSort(int *A,int p,int r)
{
    for(int j=p+1;j<=r;++j)
    {
        int key=A[r],i=j-1;
        for(;i>=p&&A[i]>key;--i)A[i+1]=A[i];
        A[i+1]=key;
    }
}

int partition(int *A,int p,int r,int pivot)
{
    swap(A[pivot],A[r]);
    int i=p-1;
    for(int j=p;j<r;++j)
    {
        if(A[j]<A[r])swap(A[++i],A[j]);
    }
    swap(A[i+1],A[r]);
    return i+1;
}

int BFPRT(int *A,int p,int r,int k)
{
    if(r-p+1<=5)
    {
        insertionSort(A,p,r);
        return A[p+k-1];
    }
    int end=p-1;
    for(int i=p;i+4<=r;i+=5)
    {
        insertionSort(A,i,i+4);
        swap(A[++end],A[i+2]);
    }
    int mid=p+(end-p)/2;
    BFPRT(A,p,end,mid);
    int q=partition(A,p,r,mid);
    int cur=q-p+1;
    if(cur==k)return A[q];
    else if(cur>k)return BFPRT(A,p,q-1,k);
    else return BFPRT(A,q+1,r,k-cur);
}

你可能感兴趣的:(median of medians(中位数的中位数))