-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRadixSort.java
More file actions
44 lines (40 loc) · 1.26 KB
/
RadixSort.java
File metadata and controls
44 lines (40 loc) · 1.26 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
package Sorting;
import java.util.Arrays;
/**
* @author Vishal Singh
* Works for small range*/
public class RadixSort {
static void countingSort(int[] arr,int n,int exp){
//10 for simplicity because a single digit number can't be more than 10.
int[] count = new int[10];
int[] output = new int[n];
for (int i = 0; i < n; i++) {
count[ (arr[i]/exp)%10 ]++;
}
for (int i = 1; i < 10; i++) {
count[i] += count[i-1];
}
for (int i = n-1; i >= 0; i--) {
output[count[(arr[i]/exp)%10]-1] = arr[i];
count[(arr[i]/exp)%10]--;
}
if (n >= 0) System.arraycopy(output, 0, arr, 0, n);
}
static void radixSort(int[] arr,int n){
//Find the largest elements number of digit
int max = Math.max(arr[0],arr[1]);
for (int i = 2; i < n; i++) {
max = Math.max(max,arr[i]);
}
//max = (int)(Math.log10(max))+1;
for (int exp = 1; max/exp > 0; exp=exp*10) {
countingSort(arr,n,exp);
}
}
public static void main(String[] args) {
int[] arr = {319,212,6,8,100,50};
int n = arr.length;
radixSort(arr,n);
System.out.println(Arrays.toString(arr));
}
}