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
##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;}
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!