Cod sursa(job #2512119)

Utilizator cristian51090Oanta Cristian cristian51090 Data 20 decembrie 2019 16:29:44
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <algorithm>
#include <iostream>
#include <iterator>
#include <fstream>
// Radix sort comparator for 32-bit two's complement integers
class radix_test
{
    const int bit; // bit position [0..31] to examine
public:
    radix_test(int offset) : bit(offset) {} // constructor

    bool operator()(int value) const // function call operator
    {
        if (bit == 31) // sign bit
            return value < 0; // negative int to left partition
        else
            return !(value & (1 << bit)); // 0 bit to left partition
    }
};

// Least significant digit radix sort
void lsd_radix_sort(int *first, int *last)
{
    for (int lsb = 0; lsb < 32; ++lsb) // least-significant-bit
    {
        std::stable_partition(first, last, radix_test(lsb));
    }
}

// Most significant digit radix sort (recursive)
void msd_radix_sort(int *first, int *last, int msb = 31)
{
    if (first != last && msb >= 0)
    {
        int *mid = std::partition(first, last, radix_test(msb));
        msb--; // decrement most-significant-bit
        msd_radix_sort(first, mid, msb); // sort left partition
        msd_radix_sort(mid, last, msb); // sort right partition
    }
}

int main(){
int a[500000],n,i;
std::ifstream fin("algsort.in");
std::ofstream fout("algsort.out");
fin>>n;for(i=0;i<n;i++)fin>>a[i];
lsd_radix_sort(a,a+n);
for(i=0;i<n;i++)
    fout << a[i]<< " ";
return 0;
}