Examples of counting and sorting by the Javascript Sorting Algorithm _ javascript skills

Source: Internet
Author: User
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 );

Related Article

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.