forked from Haresh1204/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
radixsort.cpp
70 lines (69 loc) · 1.14 KB
/
radixsort.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
69
70
#include<bits/stdc++.h>
using namespace std;
void countsort(int a[],int n,int exp)
{
int b[n];int max=a[0],min=a[0];
for(int i=0;i<n;i++)
{
if(max<a[i])
max=a[i];
if(min>a[i])
min=a[i];
}
int range=10;
int f[range];
for(int i=0;i<10;i++)
{
f[i]=0;
}
for(int i=0;i<n;i++)
{
f[a[i]/exp%10]++;
}
for(int i=1;i<range;i++)
{
f[i]=f[i]+f[i-1];
}
for(int i=n-1;i>=0;i--)
{
int pos=f[a[i]/exp%10]-1;
b[pos]=a[i];
f[a[i]/exp%10]--;
}
for(int i=0;i<n;i++)
{
a[i]=b[i];
}
}
void radixsort(int a[],int n)
{
int max=a[0];
for(int i=0;i<n;i++)
{
if(a[i]>max)
max=a[i];
}
int exp=1;
while(max>=exp)
{
countsort(a,n,exp);
exp=exp*10;
}
}
int main()
{
int n;
cout<<"ENETR NUMBER OF VALUES : ";
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
radixsort(a,n);
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
return 0;
}