哎呀 走马观花来到快排了

排序算法之前都实现过,就当练练手吧。不过见识了快排的尾递归写法-=-

#include<iostream>
#include<algorithm>
#include<memory>//the hearder file of shared_ptr
#include <vector>
#include <list>
#include <map>
#include <string>

using namespace std;

int partition(int* A, int low, int high) {
    int mid = (low + high) / 2;
    int key = A[mid];
    A[mid] = A[low];
    int last = low;

    for (int i = low + 1;i < high;i++) {
        if (A[i] < key)swap(A[++last], A[i]);
    }
    A[low] = A[last];
    A[last] = key;

    return last;
}

int h_partition(int *A, int low, int high) {
    //hoare-partition
    int i = low, j = high - 1;
    int key = A[low];

    while (true) {//分析循环实际上key值一直在被交换,若元素不互异则无法正常工作
    while (i<high&&A[i] < key)i++;
    while (j>=low&&A[j] > key)j--;
    if (i >= j)break;
    swap(A[i], A[j]);
    }
    return j;
}

void tail_qsort(int *A, int low, int high) {//尾递归版本
    if (high - low <= 1)return;//只剩一个元素

    while (low <= high) {
        int j = partition(A, low, high);
        tail_qsort(A, low, j);
        low = j + 1;
    }
}

void q_sort(int *A, int low, int high) {
    if (high - low <= 1)return;

    int j = h_partition(A, low, high);
    q_sort(A, low, j);
    q_sort(A, j + 1, high);
}

int main(void) {
    
    int a[15] = { 2,0,1,90,3,5,6,9,8,4,99,36,89,26,25 };
    tail_qsort(a, 0, 15);
    for (const int& mem : a)cout << mem << " ";

    cout << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/schsb/p/8569141.html