Home  >  Article  >  Web Front-end  >  Detailed explanation of counting sorting in JavaScript

Detailed explanation of counting sorting in JavaScript

韦小宝
韦小宝Original
2018-03-14 14:25:171242browse

This article talks about counting sorting in JavaScript. If you don’t know about counting sorting in JavaScript or are interested in counting sorting in JavaScript, then let’s take a look at this article. Okay, let’s cut the nonsense and get to the point

The core of counting sorting is to convert the input data values ​​into keys and store them in the additional arrayspace. As a sorting with linear time complexity, counting sorting requires that the input data must be an integer with a certain range.

Counting sorting animation demonstration

Detailed explanation of counting sorting in JavaScript

##JavaScript code implementation:

function countingSort(arr, maxValue) {  
    var bucket = new Array(maxValue+1),  
        sortedIndex = 0;  
        arrLen = arr.length,  
        bucketLen = maxValue + 1;  
  
    for (var i = 0; i < arrLen; i++) {  
        if (!bucket[arr[i]]) {  
            bucket[arr[i]] = 0;  
        }  
        bucket[arr[i]]++;  
    }  
  
    for (var j = 0; j < bucketLen; j++) {  
        while(bucket[j] > 0) {  
            arr[sortedIndex++] = j;  
            bucket[j]--;  
        }  
    }  
  
    return arr;}

The above is all the content of this article, if you haven’t If you know it well, you can easily master it if you can realize more of both sides by yourself!



Related recommendations:
Examples of counting sorting and radix sorting algorithms implemented in JS

The above is the detailed content of Detailed explanation of counting sorting in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn