GIF demonstration
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/eba8f47dfef894bf328a5ccc13cf5279.gif#pic_center)
Source code demonstration
import java.util.Arrays;
public class code02_RadixSort {
public static void main(String[] args) {
int[] array = generateRandomArray(100, 1000);
int[] test = copyArray(array);
Arrays.sort(test);
radixSort(array);
compareArray(array, test);
}
public static void radixSort(int[] array) {
if (array == null || array.length < 2) {
return;
}
radixSort(array, 0, array.length - 1, maxBits(array));
}
public static void radixSort(int[] array, int L, int R, int Digit) {
final int Radix = 10;
int[] bucket = new int[R - L + 1];
for (int i = 1; i <= Digit; i++) {
int[] count = new int[Radix];
for (int j = L; j < R - L + 1; j++) {
count[getDigit(array[j], i)]++;
}
for (int j = 1; j < count.length; j++) {
count[j] = count[j] + count[j - 1];
}
for (int j = R; j >= L; j--) {
bucket[count[getDigit(array[j], i)] - 1] = array[j];
count[getDigit(array[j], i)]--;
}
System.arraycopy(bucket, 0, array, L, bucket.length);
}
}
public static int maxBits(int[] array) {
int max = Integer.MIN_VALUE;
for (int j : array) {
max = Math.max(max, j);
}
int Bits = 0;
while (max != 0) {
Bits++;
max = max / 10;
}
return Bits;
}
public static int getDigit(int value, int d) {
return (int) (value / (Math.pow(10, d - 1)) % 10);
}
public static int[] generateRandomArray(int maxSize, int maxValue) {
int[] array = new int[(int) ((maxSize + 1) * Math.random())];
for (int i = 0; i < array.length; i++) {
array[i] = (int) (maxValue * Math.random());
}
return array;
}
public static void compareArray(int[] array1, int[] array2) {
if (!Arrays.equals(array1, array2)) {
System.out.println("No equals!!");
} else {
System.out.println("Success!!");
}
}
public static int[] copyArray(int[] array) {
int[] tmp = new int[array.length];
System.arraycopy(array, 0, tmp, 0, array.length);
return tmp;
}
}