forked from ghostmkg/programming-language
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRadix_Sort.cpp
68 lines (55 loc) · 1.38 KB
/
Radix_Sort.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
64
65
66
67
68
#include <bits/stdc++.h>
using namespace std;
int getMax(const vector<int>& v){
int m = v[0];
for (int i = 1; i < v.size(); i++){
if (v[i] > m){
m = v[i];
}
}
return m;
}
void countSort(vector<int>& v, int exp){
vector<int> output(v.size());
int i, count[10] = { 0 };
// Store count of occurrences
for (i = 0; i < v.size(); i++) {
count[(v[i] / exp) % 10]++;
}
// Change count[i] so that it contains the actual position of this digit in the output
for (i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
// Build the output vector
for (i = v.size() - 1; i >= 0; i--) {
output[count[(v[i] / exp) % 10] - 1] = v[i];
count[(v[i] / exp) % 10]--;
}
// Copy the output vector to v
for (i = 0; i < v.size(); i++){
v[i] = output[i];
}
}
void RadixSort(vector<int>& v){
int m = getMax(v);
// Apply counting sort to sort elements based on each digit
for (int exp = 1; m / exp > 0; exp *= 10){
countSort(v, exp);
}
}
int main(){
int n;
cout << "Enter the number of elements: ";
cin >> n;
vector<int> v(n);
cout << "Enter the elements: ";
for(int i = 0; i < n; i++){
cin >> v[i];
}
RadixSort(v);
cout << "Sorted array: ";
for (int i = 0; i < n; i++){
cout << v[i] << " ";
}
return 0;
}