Cod sursa(job #1937440)

Utilizator medicinedoctoralexandru medicinedoctor Data 23 martie 2017 22:57:05
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <vector>

using namespace std;

vector <vector <int> > a;

void read()
{
    int n, s = 65536;
    ifstream f("algsort.in");
    f >> n;
    a.resize(s + 5);

    for (int i = 0; i < n; i++)
    {
        int x;
        f >> x;
        a[x / s].push_back(x);
    }

    f.close();
}

void qs(vector <int> &a)
{
    if (a.size() < 2) 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 (size_t i = 0; i < x.size() / 2; i++)
        swap(x[i], x[x.size() - 1 - i]);
    for (size_t 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();
    }
}

void srt()
{
    for (size_t i = 0; i < a.size(); i++)
        qs(a[i]);

    ofstream f("algsort.out");

    for (size_t i = 0; i < a.size(); i++)
    {
        for (size_t j = 0; j < a[i].size(); j++)
            f << a[i][j] << ' ';
    }

    f.close();
}

int main()
{
    read();

    srt();

    return 0;
}