-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathRadix Sort.cpp
More file actions
72 lines (59 loc) · 1.09 KB
/
Radix Sort.cpp
File metadata and controls
72 lines (59 loc) · 1.09 KB
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
69
70
71
72
#include<bits/stdc++.h>
using namespace std;
void radixSort(int *arr, int &no_of_elmnts){
int min = INT_MAX;
int max = INT_MIN;
for(int i=0;i<no_of_elmnts;i++){
if(arr[i]>max){
max = arr[i];
continue;
}
if(arr[i]<min){
min=arr[i];
}
}
if(min<0){
for(int i=0;i<no_of_elmnts;i++){
arr[i]+=abs(min);
}
max+=abs(min);
}
int rounds=0;
while(max){
rounds++;
max/=10;
}
vector< list<int> > buckets;
int place_value=1;
for(int i=0;i<rounds;i++){
buckets.clear();
buckets.resize(10);
for(int j=0;j<no_of_elmnts;j++){
buckets[ (arr[j]/place_value) % 10 ].push_back(arr[j]);
}
int arr_index=0;
for(int j=0;j<10;j++){
list<int>::iterator it;
for(it=buckets[j].begin(); it!=buckets[j].end();it++){
arr[arr_index++]=*it;
}
}
place_value*=10;
}
if(min<0){
for(int i=0;i<no_of_elmnts;i++){
arr[i]+=min;
}
}
}
int main(){
// freopen("input.txt", "rd", stdin);
int no_of_elmnts;
cin>>no_of_elmnts;
int *arr = new int[no_of_elmnts];
for(int i=0;i<no_of_elmnts;i++){
cin>>arr[i];
}
radixSort(arr, no_of_elmnts);
return 0;
}