8000 Radix sort code · harshspandey1/DSA-Bootcamp-Java@5a8af23 · GitHub
[go: up one dir, main page]

Skip to content

Commit 5a8af23

Browse files
Radix sort code
1 parent de2a795 commit 5a8af23

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import java.util.*;
2+
3+
class Main {
4+
5+
public static void radixSort(int[] arr) {
6+
int max = Arrays.stream(arr).max().getAsInt();
7+
8+
// do count sort for every digit place
9+
for(int exp = 1; max/exp > 0; exp *= 10) {
10+
countSort(arr, exp);
11+
}
12+
}
13+
14+
private static void countSort(int[] arr, int exp) {
15+
int n = arr.length;
16+
int[] output = new int[n];
17+
int[] count = new int[10];
18+
19+
Arrays.fill(count, 0);
20+
21+
for(int i=0; i<n; i++) {
22+
count[(arr[i] / exp) % 10]++;
23+
}
24+
25+
System.out.println("\nCount array for " + exp + " : " + Arrays.toString(count));
26+
27+
for(int i=1; i<10; i++) {
28+
count[i] = count[i] + count[i-1];
29+
}
30+
31+
System.out.println("Updated count array " + Arrays.toString(count));
32+
33+
for(int i=n-1; i>=0; i--) {
34+
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
35+
count[(arr[i] / exp) % 10]--;
36+
}
37+
38+
System.out.println("Output array " + Arrays.toString(output));
39+
40+
System.arraycopy(output, 0, arr, 0, n);
41+
42+
}
43+
44+
public static void main(String[] args) {
45+
int[] arr = {29, 83, 471, 36, 91, 8};
46+
47+
System.out.println("Origin array: " + Arrays.toString(arr));
48+
radixSort(arr);
49+
System.out.println("Sorted array: " + Arrays.toString(arr));
50+
}
51+
}

0 commit comments

Comments
 (0)
0