概念
计数排序的核心在于将输入的数据值转化为键存储在额外开辟的数组空间中。作为一种线性时间复杂度的排序,计数排序要求输入的数据必须是有确定范围的整数。
图片演示
Java 代码实现
/**
* @ClassName: Test9
* @Description: 计数排序
* @Author: wangjie
* @Date: 2020/1/8 9:09
* @Phone: 123
*/
public class Test9 {
public static void main(String[] args) {
int[] arr = {7, 6, 13, 79, 51, 111, 58, 42, 37, 22, 31};
int maxValue = getMaxValue(arr);
countingSort(arr, maxValue);
for (Integer i : arr) {
System.out.print(i+",");
}
}
public 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;
}
public static int getMaxValue(int[] arr) {
int maxValue = arr[0];
for (int value : arr) {
if (maxValue < value) {
maxValue = value;
}
}
return maxValue;
}
}