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 57 58 59 60 61 62 63 64 65 66 67
| import java.util.Arrays;
public class RadixSort {
private static final int RADIX = 10;
private static int getDigitLength(int digit) { return (digit == 0) ? 1 : (int) Math.log10(digit) + 1; }
private static int getMaxLength(int[] arr) { int maxLength = 0; for (int e : arr) { int len = getDigitLength(e); if (len > maxLength) maxLength = len; } return maxLength; }
private static int getDigit(int x, int d) { return x / (int) (Math.pow(10, d - 1)) % 10; }
private static void countingSort(int[] arr, int d) { int[] counts = new int[RADIX]; for (int e : arr) { counts[getDigit(e, d)]++; }
for (int i = 1; i < RADIX; i++) { counts[i] += counts[i - 1]; }
int[] tmp = new int[RADIX]; for (int i = arr.length - 1; i >= 0; i--) { tmp[--counts[getDigit(arr[i], d)]] = arr[i]; } System.arraycopy(tmp, 0, arr, 0, tmp.length); }
public static void lsdRadixSort(int[] arr) { int maxLength = getMaxLength(arr); for (int d = 1; d <= maxLength; d++) { countingSort(arr, d); } }
public static void main(String[] args) {
int[] arr = {20, 90, 64, 289, 998, 365, 852, 123, 789, 456}; RadixSort.lsdRadixSort(arr); System.out.println(Arrays.toString(arr)); } }
|