Pagini recente » Cod sursa (job #1263385) | Cod sursa (job #918783) | Cod sursa (job #2320447) | Cod sursa (job #1446341) | Cod sursa (job #2316983)
/* Counting sort : linear time sorting algorithm that sorts the array in O(n + k)
where values are in range [1, k]
What if the elements are in [1, n^2] -> O(n^2) complexity worse than any comparison sorting algorithm
Solution: RADIX sort
Algorithm
Do the following for each digit i ranging from least to the most significant one
sort the input array based on the ith digit using counting sort
Coplexity O(n*#digits) where #digits ~ log(maxx)
Useful when the data has a large number of dupliucates and the value range is relatively small
*/
#include <bits/stdc++.h>
using namespace std;
const int nmax = 5e5+2;
FILE *fin = freopen("algsort.in", "r", stdin);
FILE *fout = freopen("algsort.out", "w", stdout);
int n, a[nmax];
void countingsort(int exp) {
int count[10] = {0};
int output[nmax];
for (int i = 0; i < n; ++ i)
count[(a[i]/exp)%10] ++;
// compute the position of the last element with digit i
for (int i = 1; i < 10; ++ i)
count[i] += count[i-1];
// compute the output array
for(int i = n-1; i >= 0; -- i) {
count[(a[i]/exp)%10] --;
output[count[(a[i]/exp)%10]] = a[i];
}
for (int i = 0; i < n; ++ i)
a[i] = output[i];
}
void radixsort() {
int maxx = -INT_MAX;
for (int i = 0; i < n; ++ i)
maxx = max(a[i], maxx);
// apply counting sort for every digit
for (int exp = 1; maxx/exp > 0; exp *= 10)
countingsort(exp);
}
int main() {
cin >> n;
for (int i = 0 ; i < n; ++ i)
cin >> a[i];
radixsort();
for (int i = 0; i < n; ++ i)
cout << a[i] << " ";
return 0;
}