面试常考题 荷兰国旗排序 快排的优化

题目参考

https://leetcode.com/problems/sort-colors/description/

代码实现

#include <bits/stdc++.h>
using namespace std;

void quick(vector<int> &v, int l, int r) {
    if (l >= r)
        return ;
    int p0=l,p2=r,pos=l;
    int tmp = v[p0];
    while(pos <= p2) {
        if(v[pos] == tmp)
            pos++;
        else if(v[pos] < tmp)
            swap(v[pos], v[p0]), p0++, pos++;
        else
            swap(v[pos], v[p2]), p2--;
    }
    if(p0-1 > l)
        quick(v, l, p0-1);
    if(p2+1 < r)
        quick(v, p2+1, r);
    return ;
}

int main() {
    vector<int> v{5, 3, 1, 7, 9, 9, 5, 3, 1, 7};

    int len = v.size();
    quick(v, 0, len-1);
    for(auto x : v) {
        cout << x <<" ";
    }cout<<endl;
    return 0;
}
posted @ 2019-07-09 21:07  Draymonder  阅读(246)  评论(0编辑  收藏  举报