-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRadix_sort
More file actions
60 lines (50 loc) · 1011 Bytes
/
Radix_sort
File metadata and controls
60 lines (50 loc) · 1011 Bytes
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
#include<iostream>
#define fori_n for(int i=0;i<n;i++)
using namespace std;
void countsort(int arr[],int n,int exp){
int m=0;
fori_n{
if(m<arr[i]){
m=arr[i];
}
}
int *count=(int *)calloc(m+1,sizeof(int));
fori_n{
count[(arr[i]/exp)%10]++;
}
for(int i=1;i<=m;i++){
count[i]+=count[i-1];
}
int *output=(int *)malloc(n*sizeof(int));
for(int i=n-1;i>=0;i--){
output[--count[(arr[i]/exp)%10]]=arr[i];
}
fori_n{
arr[i]=output[i];
}
free(count);
free(output);
}
void radixsort(int arr[],int n){
int max=0;
fori_n{
if(max<arr[i]){
max=arr[i];
}
}
for(int exp=1; max/exp>0; exp*=10){
countsort(arr,n,exp);
}
}
void print(int arr[],int n){
fori_n{
cout<<arr[i]<<"\t";
}
}
int main(){
int arr[]={4, 3, 12, 1, 5, 5, 3, 9};
int n=sizeof(arr)/sizeof(arr[0]);
radixsort(arr,n);
print(arr,n);
return 0;
}