基数排序是一种独立的排序思想,其排序准则就是“按位分组,再行排序”,适用于不同位数的排序。其代码如下:
public static void radixSort(int[]arr){
int [][] temp = new int[10][arr.length];
int max = Integer.MIN_VALUE; //存最大数
int [] counts = new int[10];
for(int i=0;i<arr.length;i++){
if(arr[i] > max){
max = arr[i];
}
}
int maxLength = (max+"").length; //求最大数位数
for(int i=0,n=1;i<maxLength;i++,n*=10){ //决定循环次数
for(int j=0;j<arr.length;j++){
int ys = arr[j]/n%10;
temp[ys][counts[ys]] = arr[j];
counts[ys]++;
}
if(i==0){
for(int[]nums:temp){
System.out.println(Arrays.toString(nums));
}
}
for(int k=0;k<counts.length;k++){
if(counts[k]!=0){
for(int l=0;l<counts[k];l++){
arr[index]++ = temp[k][l];
}
counts[k] = 0;
}
}
}
}
本文详细介绍了基数排序的基本概念,展示了如何利用按位分组和计数的方法对整数数组进行排序,包括代码示例。通过理解这个过程,开发者可以掌握在不同位数场景下的高效排序技术。
1521

被折叠的 条评论
为什么被折叠?



