[传统算法] 快速排序C++实现

#include 
#include 

using namespace std;

void output(vector a){
    for(int i : a)
        cout << i << ',';
    cout << endl;
}

void qsort(vector& a, int l, int r){
    if(l >= r) return;
    int k = a[l], i = l, j = r;
    while(1){
        while(i < j && k <= a[j])  j--;
        while(i < j && k >= a[i])  i++;
        if(i >= j) break;
        swap(a[i], a[j]);
    }
    swap(a[l], a[j]);
    qsort(a, l, j-1);
    qsort(a, j+1, r);
}

int main(){
    vector a = {6,6,7,3,8,9};
    
    cout << "before sort: ";
    output(a);
    qsort(a, 0, a.size()-1);
    cout << "after  sort: ";
    output(a);
    
    return 0;
}

ref: https://baike.baidu.com/item/%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95?fromtitle=%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F&fromid=2084344

你可能感兴趣的:(传统算法)