Pagini recente » Cod sursa (job #3259754) | Cod sursa (job #2604252) | Cod sursa (job #2425515) | Cod sursa (job #2633491) | Cod sursa (job #1249328)
#include <cstdio>
using namespace std;
const int NMAX = 500000;
inline int get_digit(const int value, const int base, const int exp) {
return (value / exp) % base;
}
void radix_sort(int *A, const int len) {
const int BASE = 1024;
// max_A element
int max_A = A[0], i;
for (i = 1; i < len; i++)
if (A[i] > max_A) max_A = A[i];
int B[NMAX];
for (unsigned long long exp = 1; exp < max_A; exp *= BASE) {
int bucket[BASE] = {0};
// Count elements by digit
for (i = 0; i < len; i++)
bucket[ get_digit(A[i], BASE, exp) ]++;
// Add the count from behind to use later in ordering
for (i = 1; i < BASE; i++)
bucket[i] += bucket[i-1];
// Put elements in order
for (i = len-1; i >= 0; i--)
B[ --bucket[ get_digit(A[i], BASE, exp) ] ] = A[i];
// Copy elements from B to A
for (i = 0; i < len; i++)
A[i] = B[i];
}
}
int main() {
int n, v[NMAX];
FILE * in = fopen("algsort.in", "r");
fscanf(in, "%d", &n);
for (int i = 0; i < n; ++i)
fscanf(in, "%d", &v[i]);
fclose(in);
radix_sort(v, n);
FILE * out = fopen("algsort.out", "w");
for (int i = 0; i < n; ++i)
fprintf(out, "%d ", v[i]);
//printf("%d ", v[i]);
fclose(out);
return 0;
}