Skip to content

Commit c578a4f

Browse files
authored
Create radix_sort.cpp
1 parent e7b059a commit c578a4f

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

radix_sort.cpp

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include<iostream>
2+
#include<list>
3+
#include<cmath>
4+
using namespace std;
5+
void display(int *array, int size) {
6+
for(int i = 0; i<size; i++)
7+
cout << array[i] << " ";
8+
cout << endl;
9+
}
10+
void radixSort(int *arr, int n, int max) {
11+
int i, j, m, p = 1, index, temp, count = 0;
12+
list<int> pocket[10]; //radix of decimal number is 10
13+
for(i = 0; i< max; i++) {
14+
m = pow(10, i+1);
15+
p = pow(10, i);
16+
for(j = 0; j<n; j++) {
17+
temp = arr[j]%m;
18+
index = temp/p; //find index for pocket array
19+
pocket[index].push_back(arr[j]);
20+
}
21+
count = 0;
22+
for(j = 0; j<10; j++) {
23+
//delete from linked lists and store to array
24+
while(!pocket[j].empty()) {
25+
arr[count] = *(pocket[j].begin());
26+
pocket[j].erase(pocket[j].begin());
27+
count++;
28+
}
29+
}
30+
}
31+
}
32+
int main() {
33+
int n, max;
34+
cout << "Enter the number of elements: ";
35+
cin >> n;
36+
cout << "Enter the maximum digit of elements: ";
37+
cin >> max;
38+
int arr[n]; //create an array with given number of elements
39+
cout << "Enter elements:" << endl;
40+
for(int i = 0; i<n; i++) {
41+
cin >> arr[i];
42+
}
43+
cout << "Data before Sorting: ";
44+
display(arr, n);
45+
radixSort(arr, n, max);
46+
cout << "Data after Sorting: ";
47+
display(arr, n);
48+
}

0 commit comments

Comments
 (0)