Counting sorting is an efficient linear sorting. It calculates the number of elements in a collection to determine how the set is arranged. Counting sorting does not require data comparison, the Counting sort mentioned above is a stable sorting algorithm. Count sorting uses an additional array Count_arr, where the I-th element is the number of elements whose value is equal to I in the Arr to be sorted array. Then, sort the elements in Arr to the correct position based on the array Count_arr.
There are four steps:
1. Find the largest and smallest elements in the array to be sorted
2. count the number of times each element with a value of I appears in the array, and store the I entry of the array Count_arr
3. accumulate all counts (from the first element in Count_arr, each item is added to the previous one)
4. Reverse traversal of the original array: place each element I in the Count_arr (I) entry of the new array, and subtract Count_arr (I) From 1 for each element.
Instance:
The Code is as follows:
/**
* Counting sorting is a non-comparison-based sorting algorithm,
* This algorithm was proposed by Harold H. Seward in 1954.
* Its advantage is that when sorting integers within a certain range,
* Its complexity is random (n + k) (where k is the Integer Range ),
* Faster than any sort algorithm.
*
*/
Function countSort (arr, min, max ){
Var I, z = 0, count = [];
For (I = min; I <= max; I ++ ){
Count [I] = 0;
}
For (I = 0; I <arr. length; I ++ ){
Count [arr [I] ++;
}
For (I = min; I <= max; I ++ ){
While (count [I] --> 0 ){
Arr [z ++] = I;
}
}
Return arr;
}
// Test
Var I, arr = [];
For (I = 0; I <100; I ++ ){
Arr. push (Math. floor (Math. random () * (141 )));
}
CountSort (arr, 0,140 );