Cod sursa(job #2442713)

Utilizator ShayTeodor Matei Shay Data 24 iulie 2019 22:48:10
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <stdio.h>
#include <string.h>

#define RADIX 0xFF
#define RADIX_SIZE 1 << 8
#define BUFFER_SIZE 1 << 17
#define NMAX 500000

char buffer[BUFFER_SIZE];
int pos = BUFFER_SIZE;
int n, v[NMAX], count[RADIX_SIZE], temp[NMAX], byte;

inline int read() {
    int x = 0;
    char c = getchar_unlocked();

    while (!('0' <= c && c <= '9')) {
        c = getchar_unlocked();
    }

    while ('0' <= c && c <= '9') {
        x = (x << 3) + (x << 1) + (c - '0');
        c = getchar_unlocked();
    }

    return x;
}

inline void print(int x) {
    char snum[65];
    int i = 0;

    do {
        snum[i++] = x % 10 + '0';
        x /= 10;
    } while (x);

    --i;

    while (i >= 0) {
        putchar(snum[i--]);
    }

    putchar(' ');
}

inline int get_byte(int x, int byte) {
    return (x >> (byte * 8)) & RADIX;   
}

inline void counting_sort() {
    memset(count, 0, sizeof(count));

    for (int i = 0 ; i < n ; ++i) {
        count[get_byte(v[i], byte)]++;
    }

    for (int i = 1 ; i <= RADIX ; ++i) {
        count[i] += count[i - 1];
    }

    for (int i = n - 1; i >= 0 ; --i) {
        temp[--count[get_byte(v[i], byte)]] = v[i];
    }

    for (int i = 0 ; i < n ; ++i) {
        v[i] = temp[i];
    }
}

inline void radix_sort() {
    for (; byte < 4 ; ++byte) {
        counting_sort();
    }
}

int main() {
    freopen("algsort.in", "r", stdin);
    freopen("algsort.out", "w", stdout);
    
    n = read();
    
    for (int i = 0 ; i < n ; ++i) {
        v[i] = read();
    }

    radix_sort();
    
    for (int i = 0 ; i < n ; ++i) {
        print(v[i]);
    }

    return 0;
}