美文网首页
非递归快排

非递归快排

作者: 不知名小号 | 来源:发表于2020-04-15 17:09 被阅读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] << " ";
        }
    }
    
    

    相关文章

      网友评论

          本文标题:非递归快排

          本文链接:https://www.haomeiwen.com/subject/wixhvhtx.html