Cod sursa(job #2386664)

Utilizator PletoPletosu Cosmin-Andrei Pleto Data 23 martie 2019 12:50:09
Problema Sortare prin comparare Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>
#include <stack>

using namespace std;

ifstream fin("algsort.in");
ofstream fout("algsort.out");

int N;
stack <int> stk, aux_stk;

void sort(stack <int>* S) {
    if (S->empty()) {
        return;
    }
    int pivot = S->top();
    S->pop();

    stack <int>* left = new stack<int>();
    stack <int>* right = new stack<int>();

    while (!S->empty()) {
        int y = S->top();
        if (y < pivot) {
            left->push(y);
        } else {
            right->push(y);
        }
        S->pop();
    }
    sort(left);
    sort(right);

    stack <int> tmp;
    while (!right->empty()) {
        tmp.push(right->top());
        right->pop();
    }
    tmp.push(pivot);
    while (!left->empty()) {
        tmp.push(left->top());
        left->pop();
    }
    while (!tmp.empty()) {
        S->push(tmp.top());
        tmp.pop();
    }
}

int main() {
    fin >> N;
    for (int x, i = 0; i < N; ++i) {
        fin >> x;
        aux_stk.push(x);
    }

    sort(&aux_stk);

    while (!aux_stk.empty()) {
        stk.push(aux_stk.top());
        aux_stk.pop();
    }

    while (!stk.empty()) {
        fout << stk.top() << ' ';
        stk.pop();
    }
    fout << '\n';

    return 0;
}