Cod sursa(job #646159)

Utilizator phookAlex Gherghisan phook Data 10 decembrie 2011 23:20:57
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <cstring>
#include <fstream>

using namespace std;

typedef unsigned char byte;

inline byte getByte(byte b, unsigned a) {
    return (a >> (b << 3)) & 0xff;
}

void sortByByte(byte b, unsigned n, unsigned *src, unsigned *dst) {
    unsigned count[256], index[256], i;
    memset(count, 0, sizeof(count));
    for(i = 0; i < n; ++i)
        ++count[getByte(b, src[i])];
    index[0] = 0;
    for(i = 1; i < 256; ++i)
        index[i] = index[i - 1] + count[i - 1];
    for(i = 0; i < n; ++i)
        dst[index[getByte(b, src[i])]++] = src[i];
}

void radix(unsigned *data, int n) {
    unsigned *temp = new unsigned[n];
    sortByByte(0, n, data, temp);
    sortByByte(1, n, temp, data);
    sortByByte(2, n, data, temp);
    sortByByte(3, n, temp, data);
    delete[] temp;
}

int main() {
    ifstream in("algsort.in");
    ofstream out("algsort.out");
    unsigned n, *data, i;

    in >> n;
    data = new unsigned[n];
    for(i = 0; i < n; ++i)
        in >> data[i];

    radix(data, n);
    for(i = 0; i < n; ++i)
        out << data[i] << " ";

    in.close();
    out.close();

    return 0;
}