Pagini recente » Cod sursa (job #2731410) | Cod sursa (job #2889519) | Cod sursa (job #2498011) | Cod sursa (job #2121934) | Cod sursa (job #2512119)
#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;
}