Skip to content

Commit c6cb7f7

Browse files
Merge pull request #339 from thesmartdeveloperr/main
add the radix sort algorithm in cpp
2 parents 9ce47d3 + 7727025 commit c6cb7f7

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
int getMax(int arr[], int n){
5+
int mx = arr[0];
6+
for (int i = 1; i < n; i++)
7+
if (arr[i] > mx)
8+
mx = arr[i];
9+
return mx;
10+
}
11+
12+
void countSort(int arr[], int n, int exp)
13+
{
14+
int output[n];
15+
int i, count[10] = { 0 };
16+
17+
for (i = 0; i < n; i++)
18+
count[(arr[i] / exp) % 10]++;
19+
20+
for (i = 1; i < 10; i++)
21+
count[i] += count[i - 1];
22+
23+
for (i = n - 1; i >= 0; i--) {
24+
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
25+
count[(arr[i] / exp) % 10]--;
26+
}
27+
28+
for (i = 0; i < n; i++)
29+
arr[i] = output[i];
30+
}
31+
//the main function which does radix sort
32+
void radixsort(int arr[], int n)
33+
{
34+
int m = getMax(arr, n);
35+
36+
for (int exp = 1; m / exp > 0; exp *= 10)
37+
countSort(arr, n, exp);
38+
}
39+
//driver function
40+
int main()
41+
{
42+
int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 };
43+
int n = sizeof(arr) / sizeof(arr[0]);
44+
radixsort(arr, n);
45+
for(int i = 0; i < n; i++)
46+
cout << arr[i] << " ";
47+
return 0;
48+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Radix Sort
2+
3+
The idea of Radix Sort is to do digit by digit sort starting from least significant digit to most significant digit. Radix sort uses counting sort as a subroutine to sort.

0 commit comments

Comments
 (0)