Cod sursa(job #2386662)

Utilizator PletoPletosu Cosmin-Andrei Pleto Data 23 martie 2019 12:47:36
Problema Sortare prin comparare Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 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;
    stack <int> right;

    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;
}