Cod sursa(job #978478)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 28 iulie 2013 21:00:36
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

const int digits = 2;       //Digits
const int r = 16;           //Bits
const int radix = 1 << r;   //Buckets
const int mask = radix - 1;

void RadixSort( vector<int>& a )
{
    const int SIZE = a.size();

    vector <int> b( SIZE );
    vector <int> bucket( radix );

    for ( int i = 0, shift = 0; i < digits; i++, shift += r )
    {
        for ( int j = 0; j < radix; ++j )
                bucket[j] = 0;

        for ( int j = 0; j < SIZE; ++j )
                ++bucket[ ( a[j] >> shift ) & mask ];

        for ( int j = 1; j < radix; j++ )
                bucket[j] += bucket[j - 1];

        for ( int j = SIZE - 1; j >= 0; --j )
                b[ --bucket[ ( a[j] >> shift ) & mask ] ] = a[j];

        for ( int j = 0; j < SIZE; ++j )
                a[j] = b[j];
    }
}

void read( vector<int>& a )
{
    ifstream f("algsort.in");

    int n;

    f >> n;

    for ( int i = 1, x; i <= n; i++ )
    {
        f >> x;
        a.push_back( x );
    }

    f.close();
}

void write( vector<int> a )
{
    ofstream g("algsort.out");

    for ( int i = 0; i < a.size(); i++ )
            g << a[i] << " ";

    g << "\n";

    g.close();
}

int main()
{
    vector<int> v;

    read(v);
    RadixSort(v);
    write(v);

    return 0;
}