Skip to content

Commit f53e9e5

Browse files
vimdemaibin
authored andcommitted
BAEL-3194 Radix Sort in Java (eugenp#7700)
1 parent b3323d5 commit f53e9e5

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.baeldung.algorithms.radixsort;
2+
3+
import java.util.Arrays;
4+
5+
public class RadixSort {
6+
7+
public static void sort(int numbers[]) {
8+
int maximumNumber = findMaximumNumberIn(numbers);
9+
10+
int numberOfDigits = calculateNumberOfDigitsIn(maximumNumber);
11+
12+
int placeValue = 1;
13+
14+
while (numberOfDigits-- > 0) {
15+
applyCountingSortOn(numbers, placeValue);
16+
placeValue *= 10;
17+
}
18+
}
19+
20+
private static void applyCountingSortOn(int[] numbers, int placeValue) {
21+
int range = 10; // radix or the base
22+
23+
int length = numbers.length;
24+
int[] frequency = new int[range];
25+
int[] sortedValues = new int[length];
26+
27+
for (int i = 0; i < length; i++) {
28+
int digit = (numbers[i] / placeValue) % range;
29+
frequency[digit]++;
30+
}
31+
32+
for (int i = 1; i < 10; i++) {
33+
frequency[i] += frequency[i - 1];
34+
}
35+
36+
for (int i = length - 1; i >= 0; i--) {
37+
int digit = (numbers[i] / placeValue) % range;
38+
sortedValues[frequency[digit] - 1] = numbers[i];
39+
frequency[digit]--;
40+
}
41+
42+
System.arraycopy(sortedValues, 0, numbers, 0, length);
43+
}
44+
45+
private static int calculateNumberOfDigitsIn(int number) {
46+
return (int) Math.log10(number) + 1; // valid only if number > 0
47+
}
48+
49+
private static int findMaximumNumberIn(int[] arr) {
50+
return Arrays.stream(arr).max().getAsInt();
51+
}
52+
53+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.baeldung.algorithms.radixsort;
2+
3+
import static org.junit.Assert.assertArrayEquals;
4+
5+
import org.junit.Test;
6+
7+
public class RadixSortUnitTest {
8+
9+
@Test
10+
public void givenUnsortedArrayWhenRadixSortThenArraySorted() {
11+
int[] numbers = { 387, 468, 134, 123, 68, 221, 769, 37, 7 };
12+
RadixSort.sort(numbers);
13+
int[] numbersSorted = { 7, 37, 68, 123, 134, 221, 387, 468, 769 };
14+
assertArrayEquals(numbersSorted, numbers);
15+
}
16+
}

0 commit comments

Comments
 (0)