An example of counting sort in JavaScript sort algorithm

Source: Internet
Author: User
Tags comparison min sort

  Counting sort is an efficient linear sort that determines how the collection is arranged by calculating the number of Chuxiang of elements in a set, and counting sorts do not require data comparisons, all of which are described above in terms of operational efficiency

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. It is divided into four steps: 1. Find the largest and smallest element 2 in the array to be sorted. Counts the number of occurrences of an element in an array that has a value of I, in item 3 of the array Count_arr. Adds up all counts (starting with the first element in Count_arr, adding each item to the previous item) 4. Backward traversal of the original array: put each element I in the new array of Count_arr (i), each element will be Count_arr (i) minus 1   Example:     code as follows:/**  * The counting sort is a non comparison based sorting algorithm, which was proposed by Harold H. Seward in 1954.  *  * its advantage is that when sorting a range of integers,  * its complexity to 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 = [];       F or (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;   &N Bsp    } &nbsP  }     return arr; }  //test   var i, arr = [];   for (i = 0; i < i++) {    Arr.push (Math.floor (Math.random () * ());}   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.