-
Notifications
You must be signed in to change notification settings - Fork 7
/
69_RadixSort.cpp
63 lines (60 loc) · 1.15 KB
/
69_RadixSort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
using namespace std;
int getMax(int arr[], int n)
{
int maxN = arr[0];
for (int i = 1; i < n; i++)
{
maxN = max(maxN, arr[i]);
}
return maxN;
}
void countSort(int arr[], int n, int pos)
{
int countArr[10] = {0};
int brr[n];
for (int i = 0; i < n; i++)
{
countArr[(arr[i] / pos) % 10]++;
}
for (int i = 1; i <= 9; i++)
{
countArr[i] = countArr[i] + countArr[i - 1];
}
for (int i = n - 1; i >= 0; i--)
{
brr[countArr[(arr[i] / pos) % 10] - 1] = arr[i];
countArr[(arr[i] / pos) % 10]--;
}
for (int i = 0; i < n; i++)
{
arr[i] = brr[i];
}
}
void radixSort(int arr[], int n)
{
int maxi = getMax(arr, n);
for (int pos = 1; maxi / pos > 0; pos *= 10)
{
countSort(arr, n, pos);
}
}
int main()
{
int arr[10] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
int k = 9;
int n = 10;
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
cout << endl;
radixSort(arr, n);
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
return 0;
}