Cod sursa(job #2297947)

Utilizator AkrielAkriel Akriel Data 6 decembrie 2018 20:41:09
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.78 kb
#include <bits/stdc++.h>

namespace Utility{
    const int U_MAX_NUMBERS = 1e7+5;
    const int U_MASK = (1<<8)-1;
    const int U_TOTAL_LAYERS = 2;

    int U_negativeValues[U_MAX_NUMBERS][U_TOTAL_LAYERS];
    int U_positiveValues[U_MAX_NUMBERS][U_TOTAL_LAYERS];

    int U_position[U_MASK];

	inline void initialize(){
		std::ios_base::sync_with_stdio(false);
		std::cin.tie(0);
	}

    inline void radixSortAlgorithm(int values[][U_TOTAL_LAYERS], int totalNumbers){
        for ( int shift = 0; shift <= 24; shift += 8 ){

            for ( int index = 1; index <= totalNumbers; index++ ){
                U_position[(values[index][0] >> shift) & U_MASK]++;
            }

            for ( int bits = 1; bits <= U_MASK; bits++ ){
                U_position[bits] += U_position[bits-1];
            }

            for ( int index = totalNumbers; index >= 1; index-- ){
                values[U_position[(values[index][0] >> shift) & U_MASK]--][1] = values[index][0];
            }

            for ( int bits = 0; bits <= U_MASK; bits++ ){
                U_position[bits] = 0;
            }

            for ( int index = 1; index <= totalNumbers; index++ ){
                values[index][0] = values[index][1];
            }
        }
    }

    inline void radixSort(int values[], int totalNumbers){

        int totalNegative = 0;
        int totalPositive = 0;

        for ( int index = 0; index < totalNumbers; index++ ){
            if ( values[index] >= 0 ){
                U_positiveValues[++totalPositive][0] = values[index];
            }
            else{
                U_negativeValues[++totalNegative][0] = values[index]*-1;
            }
        }

        radixSortAlgorithm(U_negativeValues, totalNegative);
        radixSortAlgorithm(U_positiveValues, totalPositive);

        int currentIndex = 0;
        for ( int index = totalNegative; index >= 1; index-- ){
            values[currentIndex] = U_negativeValues[index][0]*-1;
            currentIndex++;
        }
        for ( int index = 1; index <= totalPositive; index++ ){
            values[currentIndex] = U_positiveValues[index][0];
            currentIndex++;
        }
    }
}

using namespace std;
using namespace Utility;

ifstream fin("algsort.in");
ofstream fout("algsort.out");

const int MAX_NUMBERS = 5e5+5;

int values[MAX_NUMBERS];
int totalNumbers;

inline void readVariables(){
    fin >> totalNumbers;
    for (int index = 0; index < totalNumbers; index++){
        fin >> values[index];
    }
}

inline void displayNumbers(){
    for (int index = 0; index < totalNumbers; index++){
        fout << values[index] << " ";
    }
}

int main(){
	initialize();
	readVariables();
	radixSort(values, totalNumbers);
	displayNumbers();
    return 0;
}