1. 排序思路
- 获得最大数的位数
- 新建:桶数组 + 桶数据记录数组
- 循环,入桶+出桶
3.1 入桶:每个数据分别入相应的桶
3.2 出桶:遍历所有的桶,按桶的顺序依次取出数据,并放入原数组
2. 代码实现
public static int[] radixSort(int[] array) {
int[] sortedArray = new int[array.length];
for (int i = 0; i < array.length; i++) {
sortedArray[i] = array[i];
}
int maxNumber = sortedArray[0];
for (int number : sortedArray) {
if (number > maxNumber) {
maxNumber = number;
}
}
int maxDigit = (maxNumber + "").length();
int[][] bucketArray = new int[10][sortedArray.length];
int[] bucketNumberCountArray = new int[10];
for (int digitCount = 0, digit = 1; digitCount < maxDigit; digitCount++, digit *= 10) {
for (int arrayCount = 0; arrayCount < sortedArray.length; arrayCount++) {
int digitOfNumber = sortedArray[arrayCount] / digit % 10;
bucketArray[digitOfNumber][bucketNumberCountArray[digitOfNumber]] = sortedArray[arrayCount];
bucketNumberCountArray[digitOfNumber]++;
}
int arrayCount = 0;
for (int bucketCount = 0; bucketCount < bucketArray.length; bucketCount++) {
if (bucketNumberCountArray[bucketCount] != 0) {
for (int validNumberCount = 0; validNumberCount < bucketNumberCountArray[bucketCount]; validNumberCount++) {
sortedArray[arrayCount++] = bucketArray[bucketCount][validNumberCount];
}
bucketNumberCountArray[bucketCount] = 0;
}
}
}
return sortedArray;
}
}