TheAlgorithms-C-Plus-Plus/Sorting/Radix Sort.cpp

68 lines
1.1 KiB
C++
Raw Normal View History

2016-11-22 13:21:07 +08:00
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstring>
using namespace std;
2019-08-21 10:10:08 +08:00
void radixsort(int a[], int n)
{
2016-11-22 13:21:07 +08:00
int count[10];
int output[n];
2019-08-21 10:10:08 +08:00
memset(output, 0, sizeof(output));
memset(count, 0, sizeof(count));
2016-11-22 13:21:07 +08:00
int max = 0;
for (int i = 0; i < n; ++i)
{
2019-08-21 10:10:08 +08:00
if (a[i] > max)
2016-11-22 13:21:07 +08:00
{
max = a[i];
}
}
int maxdigits = 0;
2019-08-21 10:10:08 +08:00
while (max)
{
2016-11-22 13:21:07 +08:00
maxdigits++;
2019-08-21 10:10:08 +08:00
max /= 10;
2016-11-22 13:21:07 +08:00
}
2019-08-21 10:10:08 +08:00
for (int j = 0; j < maxdigits; j++)
{
for (int i = 0; i < n; i++)
{
int t = pow(10, j);
count[(a[i] % (10 * t)) / t]++;
2016-11-22 13:21:07 +08:00
}
int k = 0;
2019-08-21 10:10:08 +08:00
for (int p = 0; p < 10; p++)
{
for (int i = 0; i < n; i++)
{
int t = pow(10, j);
if ((a[i] % (10 * t)) / t == p)
{
2016-11-22 13:21:07 +08:00
output[k] = a[i];
k++;
}
}
}
2019-08-21 10:10:08 +08:00
memset(count, 0, sizeof(count));
2016-11-22 13:21:07 +08:00
for (int i = 0; i < n; ++i)
{
a[i] = output[i];
}
}
}
2019-08-21 10:10:08 +08:00
void print(int a[], int n)
{
2016-11-22 13:21:07 +08:00
for (int i = 0; i < n; ++i)
{
2019-08-21 10:10:08 +08:00
cout << a[i] << " ";
2016-11-22 13:21:07 +08:00
}
2019-08-21 10:10:08 +08:00
cout << endl;
2016-11-22 13:21:07 +08:00
}
int main(int argc, char const *argv[])
{
int a[] = {170, 45, 75, 90, 802, 24, 2, 66};
2019-08-21 10:10:08 +08:00
int n = sizeof(a) / sizeof(a[0]);
radixsort(a, n);
print(a, n);
2016-11-22 13:21:07 +08:00
return 0;
}