分治法快速排序

#include <iostream>
#include <cstdlib>
#include<cstring>
using namespace std;

template<typename Type>
int partition(Type a[], int low, int high)
{
    //返回基准元素的最终位置
    a[0] = a[low];//辅助空间a[0]
    Type key = a[low];//用子表的第一个记录作为枢纽记录
    while(low < high){
        while(low < high && a[high] >= key)
            --high;
        a[low] = a[high];//将比枢纽元素小的移到低端
        while(low < high && a[low] <= key)
            ++low;
        a[high] = a[low];//将比枢纽元素大的移到高端
    }
    a[low] = a[0];
    return low;//返回基准元素的最终位置
}

template <typename Type>
void quickSort(Type a[], int low, int high)
{
    if(low < high){
        int q = partition(a, low, high);
        quickSort(a, low, q - 1);
        quickSort(a, q + 1, high);
    }
}

template <typename Type>
int randomizedPartition(Type a[], int low, int high)
{
    //从子序列中随机找出一个做基准元素
    int i = low + rand()%(high - low + 1);
    Type temp = a[i];
    a[i] = a[low];
    a[low] = temp;
    return partition(a, low, high);
}

template <typename Type>
void randomizedQuickSort(Type a[], int low, int high)
{
    if(low < high){
        int q = randomizedPartition(a, low, high);
        randomizedQuickSort(a, low, q - 1);
        randomizedQuickSort(a, q + 1, high);
    }
}
int main()
{
    int L[11] = {-1, 0, 1, 3, 5, 2, 4, 6, 8, 9, 7};
    randomizedQuickSort(L, 1, 10);//quickSort(L, 1, 10);
    for(int i = 1; i <= 10; i ++)
        cout<<L[i]<<" ";
    cout<<endl;
    system("pause");
}
原文地址:https://www.cnblogs.com/tomctx/p/2476891.html