An example of the counting-ordering of JavaScript sort algorithm _javascript skill

Source: Internet
Author: User

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);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.