Skip to content

Commit 318c323

Browse files
authored
Create RadixSort.cpp
1 parent 8084419 commit 318c323

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

C++/RadixSort.cpp

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#include<iostream>
2+
using namespace std;
3+
4+
// A utility function to get maximum value in arr[]
5+
int getMax(int arr[], int n)
6+
{
7+
int mx = arr[0];
8+
for (int i = 1; i < n; i++)
9+
if (arr[i] > mx)
10+
mx = arr[i];
11+
return mx;
12+
}
13+
14+
// A function to do counting sort of arr[] according to
15+
// the digit represented by exp.
16+
void countSort(int arr[], int n, int exp)
17+
{
18+
int output[n]; // output array
19+
int i, count[10] = {0};
20+
21+
// Store count of occurrences in count[]
22+
for (i = 0; i < n; i++)
23+
count[ (arr[i]/exp)%10 ]++;
24+
25+
// Change count[i] so that count[i] now contains actual
26+
// position of this digit in output[]
27+
for (i = 1; i < 10; i++)
28+
count[i] += count[i - 1];
29+
30+
// Build the output array
31+
for (i = n - 1; i >= 0; i--)
32+
{
33+
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
34+
count[ (arr[i]/exp)%10 ]--;
35+
}
36+
37+
// Copy the output array to arr[], so that arr[] now
38+
// contains sorted numbers according to current digit
39+
for (i = 0; i < n; i++)
40+
arr[i] = output[i];
41+
}
42+
43+
// The main function to that sorts arr[] of size n using
44+
// Radix Sort
45+
void radixsort(int arr[], int n)
46+
{
47+
// Find the maximum number to know number of digits
48+
int m = getMax(arr, n);
49+
50+
// Do counting sort for every digit. Note that instead
51+
// of passing digit number, exp is passed. exp is 10^i
52+
// where i is current digit number
53+
for (int exp = 1; m/exp > 0; exp *= 10)
54+
countSort(arr, n, exp);
55+
}
56+
57+
// A utility function to print an array
58+
void print(int arr[], int n)
59+
{
60+
for (int i = 0; i < n; i++)
61+
cout << arr[i] << " ";
62+
}
63+
64+
// Driver program to test above functions
65+
int main()
66+
{
67+
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
68+
int n = sizeof(arr)/sizeof(arr[0]);
69+
radixsort(arr, n);
70+
print(arr, n);
71+
return 0;
72+
}

0 commit comments

Comments
 (0)