Skip to content

Commit 5b70773

Browse files
authored
Create Radix sort in c++ (#366)
1 parent 91d07c6 commit 5b70773

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

CPP/sorting/Radix sort in c++

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#include <bits/stdc++.h>
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+
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
33+
count[(arr[i] / exp) % 10]--;
34+
}
35+
36+
// Copy the output array to arr[], so that arr[] now
37+
// contains sorted numbers according to current digit
38+
for (i = 0; i < n; i++)
39+
arr[i] = output[i];
40+
}
41+
42+
// The main function to that sorts arr[] of size n using
43+
// Radix Sort
44+
void radixsort(int arr[], int n)
45+
{
46+
// Find the maximum number to know number of digits
47+
int m = getMax(arr, n);
48+
49+
// Do counting sort for every digit. Note that instead
50+
// of passing digit number, exp is passed. exp is 10^i
51+
// where i is current digit number
52+
for (int exp = 1; m / exp > 0; exp *= 10)
53+
countSort(arr, n, exp);
54+
}
55+
56+
// A utility function to print an array
57+
void print(int arr[], int n)
58+
{
59+
for (int i = 0; i < n; i++)
60+
cout << arr[i] << " ";
61+
}
62+
63+
// Driver Code
64+
int main()
65+
{
66+
int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 };
67+
int n = sizeof(arr) / sizeof(arr[0]);
68+
69+
// Function Call
70+
radixsort(arr, n);
71+
print(arr, n);
72+
return 0;
73+
}

0 commit comments

Comments
 (0)