思路:
首先: 计算出待排序数组中最大值max与最小值min的差距,建立一个桶数组count;
其次: 用count数组的下标i来表示与最小值的差距,count[i]中来存待排序数组中有多少个与最小值的差距
最后: 我们知道count的下标i是表示与最小值的差距,所以说i+min就代表待排序数组中的原始值,count[i]表示统计原数组中与最小值差距为i的数目,所以可以根据这两点将count[i]中的值按顺序依次打印出来就是排序后的数。
public static int[] countingSort(int[] A, int n) {
if(A == null || A.length < 2){
return A;
}
int max = A[0];
int min = A[0];
for(int i = 0;i < A.length;i++){
max = Math.max(max, A[i]);
min = Math.min(min, A[i]);
}
int[] countArr = new int[max - min + 1];
//countArr的下标i表示与最小值的差距 ,countArr[i]中存的值代表有多少个下标i
for(int i = 0;i < A.length;i++){
countArr[A[i] - min]++;
}
int index = 0;
for(int i = 0;i < countArr.length;i++){
while(countArr[i] > 0){
A[index++] = i + min;
countArr[i]--;
}
}
return A;
}