The counting sort (counting sort) is a stable sort algorithm. The count sort uses an extra array of Count_arr, where the first element is the number of elements in the array arr that are to be sorted to the value equal to I. The elements in the Arr are then ranked in the correct position according to the array Count_arr.
is divided into four steps:
1. Find the largest and smallest elements in the array to be sorted
2. Count the number of occurrences of an element of each value in the array, in the Count_arr of the array
3. Add to all counts (starting with the first element in the Count_arr, adding each item to the previous item)
4. Reverse traverse the original array: put each element I in the new array of the first Count_arr (i), each element will be Count_arr (i) minus 1
Instance:
Copy Code code as follows:
/**
* Counting sort is a sort algorithm that is not based on comparison,
* The algorithm was presented by Harold H. Seward in 1954.
* Its advantage is that in a certain range of integers in the sort,
* Its complexity is 0 (n+k) (where K is the range of integers),
* Faster than any comparison 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 < i++) {
Arr.push (Math.floor (Math.random () * (141)));
}
Countsort (arr, 0, 140);