Cod sursa(job #1854507)

Utilizator SlevySlevoaca Stefan-Gabriel Slevy Data 22 ianuarie 2017 20:01:39
Problema Sortare prin comparare Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.42 kb
#include <iostream>
#include <fstream>
#include <string.h>
#define TOTAL_BYTE 4
#define get_byte(x) ((x >> (8*byte)) & 0xFF)
#define RADIX_SIZE 8
#define BUFF_SIZE 100001

using namespace std;

ifstream in("algsort.in");
ofstream out("algsort.out");
int *a, n;
char BUFF[BUFF_SIZE];
int pos = 0;
char BUFFW[BUFF_SIZE];
char LBUFF[15];

void Read(int &a)
{
    while(!isdigit(BUFF[pos]))
        if(++pos == BUFF_SIZE)
            in.read(BUFF,BUFF_SIZE), pos = 0;
    a = 0;
    while(isdigit(BUFF[pos]))
    {
        a = a * 10 + (BUFF[pos] - '0');
        if(++pos == BUFF_SIZE)
            in.read(BUFF,BUFF_SIZE), pos = 0;
    }
}

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;
}

char* itoa (int nr, char *str)
{
    char aux;
    int length = -1;
    while (nr)
    {
        str[++length] = (nr % 10) + '0';
        nr /= 10;
    }
    str[++length] = '\0';
    int i = strlen(str) - 1, j = 0;
    while (i > j)
    {
        aux = str[i];
        str[i] = str[j];
        str[j] = aux;
        i--;
        j++;
    }
    return str;
}

int main()
{
    Read(n);
    memset(BUFFW, 0, sizeof(char) * BUFF_SIZE);
    a = new int[n+1];
    for (int i = 1; i <= n; i++)
        Read(a[i]);
    in.close();
    RadixSort(a,n);
    int length = 0, llength;
    for (int i = 1; i <= n; i++)
    {
        itoa(a[i], LBUFF);
        strcat(LBUFF, " ");
        llength = strlen(LBUFF);
        if (length + llength >= BUFF_SIZE)
        {
            out << BUFFW;
            strcpy(BUFFW, LBUFF);
            length = llength;
        }
        else
        {
            strcat(BUFFW, LBUFF);
            length += llength;
        }
    }
    out << BUFFW << "\n";
    out.close();
    delete[] a;
    return 0;
}