JAVA-基数排序代码(低位优先)
基数排序与计数排序相似。
首先比较个位数大小–然后比较十位数大小–然后比较百位数大小…
这样我们就应该先算出数组中的最大值是多少位
计算数组的最大位数的代码为:
int[] arr = {95,94,91,98,99,90,99,93,91,100};
int max =arr[0];
for(int i=0;i<arr.length;i++) {
if(arr[i]>max) {
max = arr[i];
}
}
System.out.println(max);
//max得到的是数组的最大值
int count = 0;
while(max!=0) {
count++;
max /= 10;
}
System.out.print(count);
//count得到的是最大值的位数,也就是我们要的结果。
输出结果为:
已知每位上的数字都在0-9之间,所以计数数组的大小为10;
已知数组的最大值位数,和数组区间(就是计数数组的位数),接下来需要判断数组中个,十,百…位的大小。
全部代码为:
public static void main(String[] args) {
int[] arr = {105,104,100,103,102,101,102,100};
sort(arr);
}
public static void sort(int[] arr) {
int max =arr[0];
int min = arr[0];
for(int i=0;i<arr.length;i++) {
if(arr[i]>=max) {
max = arr[i];
}
}
System.out.println("数组中最大值为:"+max);
int count = 0;
while(max!=0) {
count++;
max /= 10;
}
System.out.println("数组中最大值的个数为:"+count);
int[] result = new int[arr.length];
int[] countarr = new int[10];
for(int i =0;i<count;i++) {
int division =(int) Math.pow(10, i);
System.out.print("10的"+i+"次方为:"+division+" ");
for(int j = 0;j<arr.length;j++) {
int num = arr[j]/division %10;
System.out.print(num+" ");
countarr[num]++;
}
for(int m = 1;m<countarr.length;m++) {
countarr[m] = countarr[m] + countarr[m-1];
}
for(int k =arr.length-1;k>=0;k--) {
int num = arr[k]/division %10;
result[--countarr[num]] = arr[k];
}
System.arraycopy(result, 0, arr, 0, arr.length);
Arrays.fill(countarr,0);
}
print(result);
}
static void print(int[] arr) {
//打印数组
for(int i = 0;i<arr.length;i++) {
System.out.print(arr[i] + " ");
}
}
输出结果为: