动图:
代码:
public class RadixSort {
public static void main(String[] args){
int[] nums = new int[]{
8, 9, 1, 7, 2, 3, 5, 4, 6, 0 };
int[] res = sort(nums);
for(int i=0; i<res.length; i++){
System.out.print(res[i] + " ");
}
}
public static int[] sort(int[] nums){
// 找出最大数的位数
int max = nums[0];
for(int i = 0; i < nums.length; i++){
if(nums[i] > max){
max = nums[i];
}
}
int maxLength = String.valueOf(max).length();
int[][] bucket = new int[10][nums.length]; // 创建10个桶,长度为数组的长度(保证最坏情况下不会越界)
int[] bucketElementCounts = new int[10]; // 创建一个一维数组记录每个桶中存放数据的个数
for(int i = 0; i < maxLength; i++){
int ratio = (int)Math.pow(10,i); // 取各十百等位数的系数
// 遍历数组放入桶中
for(int j = 0; j < nums.length; j++){
// 取出元素相应位置的值
int digitOfElement = nums[j] / ratio % 10;
bucket[digitOfElement][bucketElementCounts[digitOfElement]] = nums[j];
bucketElementCounts[digitOfElement]++;
}
// 将桶中的数据依次放回数组
int index = 0;
for(int k = 0; k < bucketElementCounts.length; k++){
if(bucketElementCounts[k] != 0){
for (int l = 0; l < bucketElementCounts[k]; l++){
nums[index] = bucket[k][l];
index++;
}
}
bucketElementCounts[k] = 0; // 清空计数数组,方便下次循环使用
}
}
return nums;
}
}