定义:
-
时间复杂度:O(n)
-
思想:
-
首先找到数组中的最大值,+1创建一个count数组
-
count数组的索引就表示元素的值,统计元素出现的次数
-
遍历count数组,索引的顺序即排序
-
-
前提
-
元素最大值不能太大
-
所有元素都是>=0的(可以改进)
-
-
适合分布比较均匀的数组的排序
/**
* 计数排序
*
* @param array 要排序的数组
* @return 返回排序结果
*/
public static int[] countSort(int[] array) {
// 1、找到原数组中的最大值
int max = Integer.MIN_VALUE;
for (int arr : array) {
if (arr > max) {
max = arr;
}
}
// 2、创建max+1的新数组
int[] count = new int[max + 1];
// 3、将原数组中的值放入新数组(索引对应关系)
for (int i = 0; i < array.length; i++) {
count[array[i]] += 1;
}
// 4、取新的值放入到原来的数组中
int k = 0;
for (int i = 0; i < count.length; i++) {
while (count[i] > 0) {
array[k++] = i;
count[i]--;
}
}
return array;
}
/**
* 计数排序
* 改进版本,映射
*
* @param array 要排序的数组
* @return 返回排序结果
*/
public static int[] countSort(int[] array) {
// 1、找到原数组中的最大值
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int arr : array) {
if (arr > max) {
max = arr;
}
if (arr < min) {
min = arr;
}
}
// 2、创建max+1的新数组
int[] count = new int[max - min + 1];
// 3、将原数组中的值放入新数组(索引对应关系)
for (int arr : array) {
count[arr - min]++;
}
// 4、取新的值放入到原来的数组中
int k = 0;
for (int i = 0; i < count.length; i++) {
while (count[i] > 0) {
array[k++] = i + min;
count[i]--;
}
}
return array;
}