JavaAlgorithms/Sorts/RadixSort.java

50 lines
1.1 KiB
Java
Raw Normal View History

2018-11-14 01:15:47 +08:00
package Sorts;
import java.util.Arrays;
class RadixSort {
2020-10-24 18:23:28 +08:00
private static int getMax(int[] arr, int n) {
int mx = arr[0];
for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i];
return mx;
}
2020-10-24 18:23:28 +08:00
private static void countSort(int[] arr, int n, int exp) {
int[] output = new int[n];
int i;
int[] count = new int[10];
Arrays.fill(count, 0);
2020-10-24 18:23:28 +08:00
for (i = 0; i < n; i++) count[(arr[i] / exp) % 10]++;
2020-10-24 18:23:28 +08:00
for (i = 1; i < 10; i++) count[i] += count[i - 1];
2020-10-24 18:23:28 +08:00
for (i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
2017-04-22 21:50:28 +08:00
}
2020-10-24 18:23:28 +08:00
for (i = 0; i < n; i++) arr[i] = output[i];
}
2017-04-22 21:50:28 +08:00
2020-10-24 18:23:28 +08:00
private static void radixsort(int[] arr, int n) {
2017-04-22 21:50:28 +08:00
2020-10-24 18:23:28 +08:00
int m = getMax(arr, n);
2020-10-24 18:23:28 +08:00
for (int exp = 1; m / exp > 0; exp *= 10) countSort(arr, n, exp);
}
2017-04-22 21:50:28 +08:00
2020-10-24 18:23:28 +08:00
static void print(int[] arr, int n) {
for (int i = 0; i < n; i++) System.out.print(arr[i] + " ");
}
2020-10-24 18:23:28 +08:00
public static void main(String[] args) {
int[] arr = {170, 45, 75, 90, 802, 24, 2, 66};
int n = arr.length;
radixsort(arr, n);
print(arr, n);
}
2017-04-22 21:50:28 +08:00
}
// Written by James Mc Dermott(theycallmemac)