TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
radix_sort.cpp
1#include <cmath>
2#include <cstdlib>
3#include <cstring>
4#include <iostream>
5
6void radixsort(int a[], int n) {
7 int count[10];
8 int* output = new int[n];
9 memset(output, 0, n * sizeof(*output));
10 memset(count, 0, sizeof(count));
11 int max = 0;
12 for (int i = 0; i < n; ++i) {
13 if (a[i] > max) {
14 max = a[i];
15 }
16 }
17 int maxdigits = 0;
18 while (max) {
19 maxdigits++;
20 max /= 10;
21 }
22 for (int j = 0; j < maxdigits; j++) {
23 for (int i = 0; i < n; i++) {
24 int t = std::pow(10, j);
25 count[(a[i] % (10 * t)) / t]++;
26 }
27 int k = 0;
28 for (int p = 0; p < 10; p++) {
29 for (int i = 0; i < n; i++) {
30 int t = std::pow(10, j);
31 if ((a[i] % (10 * t)) / t == p) {
32 output[k] = a[i];
33 k++;
34 }
35 }
36 }
37 memset(count, 0, sizeof(count));
38 for (int i = 0; i < n; ++i) {
39 a[i] = output[i];
40 }
41 }
42 delete[] output;
43}
44
45void print(int a[], int n) {
46 for (int i = 0; i < n; ++i) {
47 std::cout << a[i] << " ";
48 }
49 std::cout << std::endl;
50}
51
52int main(int argc, char const* argv[]) {
53 int a[] = {170, 45, 75, 90, 802, 24, 2, 66};
54 int n = sizeof(a) / sizeof(a[0]);
55 radixsort(a, n);
56 print(a, n);
57 return 0;
58}
double k(double x)
Another test function.
int main()
Main function.