【快速排序】QuickSort(三种实现方法)c++描述

//以下算法详解,可以在《计算机算法设计与分析》(王晓东,三版)和《数据结构》(严蔚敏)中找到详解。

#include <iostream>
using namespace std;
/*
int Random(int low,int high);

template <class Type>
void RandomizedQuickSort(Type a[],int low,int high);

*/

/*
template <class Type>
void SWAP(Type a[],int i,int j);
*/

template <class Type>
void QuickSort(Type a[],int low,int high);

template <class Type>
int Partition(Type a[],int low,int high);

int main (int argc, const char * argv[])
{
    int a[] = {-1,2,5,34,56,3,55,57}; //0位置不用,作为pivot暂存。
    int high = 7;
    int low = 1; 
    QuickSort(a, low, high);
    for (int i = 1; i<8; i++) {
        cout<<a[i]<<" ";
    }
    return 0;
}

//常规的解法 。。。。。。。。。。。。。。。。。
template <class Type>
void QuickSort(Type a[],int low,int high)
{
    if (low < high) {
        int pivot = Partition(a, low, high);
        QuickSort(a,low,pivot-1);
        QuickSort(a,pivot+1,high);
    }
}

template <class Type>
int Partition(Type a[],int low,int high) 
{
    a[0] = a[low];//pivotKey
    Type pKey = a[low];
    while (low < high) {
        while (a[high] >= pKey && low < high ) high--;
        a[low] = a[high];
        while (a[low] <= pKey && low < high) low++;
        a[high] = a[low];
    }
    a[low] = a[0];
    return low;
}


template <class Type>
void SWAP(Type a[],int i,int j)
{
    Type temp;
    temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

// 另一种partition的算法...参考《计算机算法设计与分析》...............................
/*
template <class Type>
int Partition(Type a[],int low,int high)
{
    int i = low - 1,j = high + 1;
    Type x = a[low];
    while (true) {  //i逐渐增大,j逐渐减小,之道a[i]>=x>=a[j]  
        while (a[++i] < x && i<j);
        while (a[--j] > x);
        if (i >= j) 
            break;
        SWAP(a,i,j);  //如果i<j,交换。
    }
    a[low] = a[j];
    a[j] = x;
    return j; 
}*/

//效率更高的随机化算法
/*
//因为pivot的选择对快排的影响非常大,所以采用随即化的算法,算法的稳定性更高。
//更容易达到我们期望的平均时间复杂度O(nlogn)
int Random(int low,int high)
{
    return rand()%(high - low + 1) + low; //产生一个low~high之间的随机数.
}

template <class Type>
int RandomizedPartition(Type a[],int low,int high)
{
    int pivot = Random(low,high);
    SWAP(a,pivot,low); //a[pivot] 与 a[low] 交换
    return Partition(a, low, high);
}

template <class Type>
void RandomizedQuickSort(Type a[],int low,int high)
{
    if (low < high) {
        int pivot = RandomizedPartition(a, low, high);
        RandomizedQuickSort(a,low,pivot-1);
        RandomizedQuickSort(a, pivot+1, high);
    }
}
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值