forked from rakhi2207/java-programs-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RadixSort.java
56 lines (49 loc) · 1.07 KB
/
RadixSort.java
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
package Pepcoding;
public class Radix {
public static void countSort(int[] arr,int exp)
{
int[] freq=new int[10];
for(int i:arr)
{
freq[(i/exp)%10]++;
}
//prefix sum;
int sum=0;
for(int i=0;i<freq.length;i++)
{
sum+=freq[i];
freq[i]=sum-1;
}
int[] ans=new int[arr.length];
for(int i=arr.length-1;i>=0;i--)
{
int pos=freq[(arr[i]/exp)%10];
ans[pos]=arr[i];
freq[(arr[i]/exp)%10]--;
}
for(int i=0;i<ans.length;i++)
{
arr[i]=ans[i];
}
}
public static void main(String[] args) {
int[] arr={901,216,450,299,39};
int max=Integer.MIN_VALUE;
for(int i:arr)
{
if(i>max)
{
max=i;
}
}
int exp=1;
while(max>=exp) {
countSort(arr, exp);
exp=exp*10;
}
for(int i:arr)
{
System.out.println(i);
}
}
}