1、算法思想:
第一步:找出待排序的数组中最大和最小的元素
第二步:统计数组中每个值为i的元素出现的次数
第三步:对所有的计数累加
第四步:反向填充目标数组
2、动图演示(动图来源菜鸟教程)
代码实现:
public class CountingSort {
public static void main(String[] args) {
int[] arr = {22, 34, 3, 32, 82, 55, 89, 50, 37, 5, 64, 35, 9, 70};
int len = getMaxValue(arr);
countingSort(arr, len);
for(int i : arr) {
System.out.print(i + " ");
}
}
private static int[] countingSort(int[] arr, int maxValue) {
int bucketLen = maxValue + 1;
int[] bucket = new int[bucketLen];
for (int value : arr) {
bucket[value]++;
}
int sortedIndex = 0;
for (int j = 0; j < bucketLen; j++) {
while (bucket[j] > 0) {
arr[sortedIndex++] = j;
bucket[j]--;
}
}
return arr;
}
private static int getMaxValue(int[] arr) {
int maxValue = arr[0];
for (int value : arr) {
if (maxValue < value) {
maxValue = value;
}
}
return maxValue;
}
}
运行结果:3 5 9 22 32 34 35 37 50 55 64 70 82 89