quicksort(双指针版本)

quicksort有两个版本。左右指针版本(如下)和Hoare版本(较易但复杂度略输)。
以下代码由松松提供。致谢~

#include 
#include 
using namespace std;

template 
int divide(vector& a, int low, int high) {
    T k = a[low];
    do {
        while (low < high && a[high] >= k) high--;
        if (low < high) {
            a[low] = a[high];
            low++;
        }
        while (low < high && a[low] <= k) low++;
        if (low < high) {
            a[high] = a[low];
            high--;
        }
    } while (low != high);
    a[low] = k;
    return low;
}

template 
void quickSort(vector& a, int low, int high) {
    int mid;
    if (low >= high) {
        return ;
    }
    mid = divide(a, low, high);
    quickSort(a, low, mid-1);
    quickSort(a, mid+1, high);
}

template 
void quickSort(vector& a) {
    quickSort(a, 0, a.size()-1);
}

int main()
{
    vector arr({1, 8, 2, 1, 7, 5, 3, 3, 2});
    for (int i = 0; i < arr.size(); i++) cout<

你可能感兴趣的:(quicksort(双指针版本))