Skip to content

Commit 5a2ce72

Browse files
authored
Merge pull request #205 from MJ-thunder/add-radix-sort-java
Added Radix Sort Algorithm in Java (Java/sorting/RadixSort.java)
2 parents 12b31e4 + 99c5195 commit 5a2ce72

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Java/sorting/RadixSort.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
public class RadixSort {
2+
3+
public static void radixSort(int[] arr) {
4+
int max = getMax(arr);
5+
for (int exp = 1; max / exp > 0; exp *= 10) {
6+
countSort(arr, exp);
7+
}
8+
}
9+
10+
private static int getMax(int[] arr) {
11+
int max = arr[0];
12+
for (int i = 1; i < arr.length; i++)
13+
if (arr[i] > max)
14+
max = arr[i];
15+
return max;
16+
}
17+
18+
private static void countSort(int[] arr, int exp) {
19+
int n = arr.length;
20+
int[] output = new int[n];
21+
int[] count = new int[10];
22+
23+
for (int i = 0; i < n; i++)
24+
count[(arr[i] / exp) % 10]++;
25+
26+
for (int i = 1; i < 10; i++)
27+
count[i] += count[i - 1];
28+
29+
for (int i = n - 1; i >= 0; i--) {
30+
int index = (arr[i] / exp) % 10;
31+
output[count[index] - 1] = arr[i];
32+
count[index]--;
33+
}
34+
35+
for (int i = 0; i < n; i++)
36+
arr[i] = output[i];
37+
}
38+
39+
public static void main(String[] args) {
40+
int[] arr = {170, 45, 75, 90, 802, 24, 2, 66};
41+
radixSort(arr);
42+
System.out.println("Sorted array:");
43+
for (int num : arr)
44+
System.out.print(num + " ");
45+
}
46+
}

0 commit comments

Comments
 (0)