快速排序的几种实现

通过分而治之的思想,将待排序的序列划分为两个子序列,并分别进行排序。

#include 
#include 
#include 
using namespace std;

int partition(int *a, int left, int right){
    int pivot = a[right];
    int i = left - 1;
    for(int j = left; j < right; j ++)
        if(a[j] <= pivot) swap(a[++i], a[j]);
    swap(a[i+1], a[right]);
    return i+1;
}

int partition_hoare(int *a, int left, int right){
    int pivot = a[left];
    int i = left - 1, j = right + 1;
    while(1){
        do{j --;} while(a[j] > pivot);
        do{i ++;} while(a[i] < pivot);
        if(i < j) swap(a[i], a[j]);
        else return j;
    }
}

int partition_hoare_update(int *a, int left, int right){
    int pivot = a[left];
    int i = left, j = right;
    while(i < j){
        while(i < j && a[j] >= pivot) j --;
        if(i < j) a[i++] = a[j];
        while(i < j && a[i] <= pivot) i ++;
        if(i < j) a[j--] = a[i];
    }
    a[j] = pivot;
    return j;
}

void quick_sort(int *a, int left, int right){
    if(left < right){
        //int p = partition(a, left, right);
        int p = partition_hoare(a, left, right);
        quick_sort(a, left, p-1);
        quick_sort(a, p+1, right);
    }
}

int main()
{
    int n = 1000000;
    int *a = new int[n];
    for(int i = 0; i < n; i ++) a[i] = rand();

    quick_sort(a, 0, n-1);

    //validate
    for(int i = 0; i < n; i ++)
        if(i + 1 < n && a[i] > a[i + 1]){
            cout << "error" << endl;
            break;
        }

    return 0;
}



你可能感兴趣的:(算法与数据结构)