快速排序

算法思想:对于输入的子数组a[p:r],按下面三个步骤:

1 分解:以a[p]为基准元素将a[p:r]分成三段,a[p:q-1],a[q],a[q+1:r],使a[p:q-1]中的任何元素都小于a[q],a[q+1:r]中的任何元素都大于a[q]

2 递归求解:递归的对a[p:q-1],a[q+1:r]再进行排序

3 合并:就地排序,不需要执行任何计算,便完成排序

template <class Type>
void QuikSort(Type a[],int p,int r){
    if(p<r)
    {
        int q = Partition(a,p,r);
        QuikSort(a,p,q-1);
        QuikSort(a,q+1,r);
    }
}

template <class Type>
void Oartition(Type a[],int p,int r){
    int i=p,j=r+1;
    Type x = a[p];
    while(true){
        while(a[++i]<x && i<r);
        while(a[--j]>x);
        if(i>=j)
            break;
        Swap(a[i],a[j]);
    }
    a[p] = a[j];
    a[j] = x;
    return j;
}
posted @ 2012-10-16 20:23  xingoo  阅读(279)  评论(0编辑  收藏  举报