Count sorting is a sorting algorithm that is not based on comparison. Its advantage is that when sorting integers within a certain range, its complexity is Ο(n+k) (where k is the range of integers), which is faster than any comparison sorting algorithm. Of course, this is an algorithm that sacrifices space for time.
Basic idea
The basic idea of counting and sorting is: for each input element x, determine the number of elements less than x. For example, if there are 7 elements less than x, then x should be in the 8th output position.
working process
- Preparation:
Input array:array
[1...n].
Output array:result
[1...n].
Temporarily store the array:countArray
[0...k]. array
The number of each element in the calculation is stored in thecountArray
array: thearray
value of the element in thecountArray
array is used as the subscript of the array, and the element in the array isarray
repeated once every time thecountArray
corresponding element of the array is +1.- Calculate
array
the number less than the current element in thecountArray
array = the sum of the current element and the previous element in the array. And update the data to thecountArray
array - According
countArray
to determine the current element in the array is less than the numberarray
of elements in the array ofresult
storage positions in the array.
Code
/**
* 计数排序
* @param array 待排序数组
* @param k 临时数组长度,取值为排序数组的最大值+1
* (此处是因为 array 中的元素被作为数组下标,所以数组长度为最大值+1)
*/
private static void countSort(int[] array, int k) {
//创建计数统计数组
int[] countArray = new int[k];
//计算 array 中每个元素的重复个数
for (int i = 0; i < array.length; i++) {
countArray[array[i]] += 1;
}
//计算数组中小于当前元素的元素个数
for (int i = 0; i < k; i++) {
if (i > 0) {
countArray[i] = countArray[i] + countArray[i - 1];
}
}
//结果输出数组
int[] result = new int[array.length];
//将 array 中的元素存放到 result 指定位置
for (int i = array.length - 1; i >= 0; i--) {
System.out.println("array:" + array[i] + " | countArray:" + countArray[array[i]]);
//计算存放位置(小于当前元素的数量值-1即为数组下标)
int pos = countArray[array[i]] -1;
//根据计数统计数组将数组array中的元素存放到result数组中
result[pos] = array[i];
//小于当前元素的数量值-1
countArray[array[i]] = pos;
}
System.out.println(Arrays.toString(result));
}
Late update, haha. Counting sorting feels like an algorithm that is not commonly used, but the idea is more peculiar than other comparison sorting, and it is worth understanding and learning.