非递归快排

2020-04-15  本文已影响0人  不知名小号
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
void quick_sort(vector<int> &v){
    int left = 0, right = v.size() - 1;
    stack<pair<int, int> >s;
    s.push(make_pair(left, right));
    while (!s.empty()){
        pair<int, int> t = s.top();
        s.pop();
        int left = t.first;
        int right = t.second;
        if (right <= left){
            continue;
        }
        int i = left, j = right;
        int target = v[left];
        while (i < j){
            while (i < j && v[j] >= target){
                j--;
            }
            while (i < j && v[i] <= target){
                i++;
            }
            if (i != j){
                swap(v[i], v[j]);
            }
        }
        v[left] = v[i];
        v[i] = target;
        if (left <= i - 1){
            s.push(make_pair(left, i - 1));
        }
        if (i + 1 <= right){
            s.push(make_pair(i + 1, right));
        }
    }
}
int main(){
    int n, t;
    vector<int> v;
    cin >> n;
    for (int i = 0; i < n; i++){
        cin >> t;
        v.push_back(t);
    }
    quick_sort(v);
    for (int i = 0; i < v.size(); i++){
        cout << v[i] << " ";
    }
}

上一篇下一篇

猜你喜欢

热点阅读