Cod sursa(job #1783803)

Utilizator SlevySlevoaca Stefan-Gabriel Slevy Data 19 octombrie 2016 14:47:06
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <fstream>
#define TOTAL_BYTE 4
#define get_byte(x) ((x >> (8*byte)) & 0xFF)
#define RADIX_SIZE 8

using namespace std;

ifstream in("algsort.in");
ofstream out("algsort.out");
int *a, n;

void CountSort(int a[], int b[], int byte, int n)
{
    int _count[1 << RADIX_SIZE];
    int ind[1 << RADIX_SIZE];
    int length = (1 << RADIX_SIZE) - 1;
    for (int i = 0; i <= length; i++)
        _count[i] = 0;
    for (int i = 1; i <= n; i++)
        _count[get_byte(a[i])]++;
    ind[0] = 1;
    for (int i = 1; i <= length; i++)
        ind[i] = ind[i - 1] + _count[i - 1];
    for (int i = 1; i <= n; i++)
        b[ind[get_byte(a[i])]++] = a[i];
}

void RadixSort(int a[], int n)
{
    int *temp = new int[n+1];
    for (int i = 0; i < TOTAL_BYTE; i++)
        if (i % 2 == 0)
            CountSort(a,temp,i,n);
        else
            CountSort(temp,a,i,n);
    delete[] temp;
}

int main()
{
    in >> n;
    a = new int[n+1];
    for (int i = 1; i <= n; i++)
        in >> a[i];
    in.close();
    RadixSort(a,n);
    for (int i = 1; i <= n; i++)
        out << a[i] << " ";
    out.close();
    return 0;
}