Cod sursa(job #1937328)

Utilizator medicinedoctoralexandru medicinedoctor Data 23 martie 2017 21:23:41
Problema Sortare prin comparare Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <fstream>
#include <vector>

using namespace std;

vector <int> a;

void write()
{
    ofstream cout("algsort.out");

    for (int i = 0; i < a.size(); i++)
        cout << a[i] << ' ';

    cout.close();
}

void read()
{
    int n;
    ifstream cin("algsort.in");
    cin >> n;
    a.resize(n);

    for (int i = 0; i < a.size(); i++)
        cin >> a[i];

    cin.close();
}

void qs(vector <int> &a)
{
    if (a.size() < 100)
    {
        for (int i = 0; i < a.size(); i++)
            for (int j = i + 1; j < a.size(); j++)
                if (a[j] < a[i]) swap(a[j], a[i]);

        return;
    }
    vector <int> x, z;
    int y = 0, q = a[a.size() / 2];

    for (; !a.empty(); )
    {
        int last = a[a.size() - 1];
        if (last == q) y++;
        if (last > q) z.push_back(last);
        if (last < q) x.push_back(last);
        a.pop_back();
    }

    qs(x);
    qs(z);

    for (int i = 0; i < x.size() / 2; i++)
        swap(x[i], x[x.size() - 1 - i]);
    for (int i = 0; i < z.size() / 2; i++)
        swap(z[i], z[z.size() - 1 - i]);

    for (; !x.empty(); )
    {
        int q = x[x.size() - 1];
        a.push_back(q);
        x.pop_back();
    }
    for (; y; y--)
        a.push_back(q);
    for (; !z.empty(); )
    {
        int q = z[z.size() - 1];
        a.push_back(q);
        z.pop_back();
    }
}

int main()
{
    read();

    qs(a);

    write();

    return 0;
}