This article introduces the method of implementing counting sorting in js (upgraded version)
In the original counting sorting, the volume of the bucket needs to be one that can contain all possible occurrences from the minimum value to the maximum value number. Here we can replace the bucket with an object, taking advantage of the automatic sorting of objects and the inability to have key-value pairs with the same attribute name. We do not need an ordered volume bucket, and can just add key-value pairs at will. The code is as follows
var ary=[23,14,12,24,53,31,53,35,46,12,62,23]
The code example is as follows:
function countSort(arr){ let obj={}; //遍历原数组,给对象新增键值对,如果已经存在就对应的属性值++,如果不存在则新增键值对 for(let i=0;i<arr.length;i++){ if(!obj[arr[i]]){ obj[arr[i]]=1; }else{ obj[arr[i]]++; } } let index=0; //遍历对象属性名,按顺序放回覆盖原数组 for(let key in obj){ while(obj[key]>0){ arr[index]=Number(key); obj[key]--; index++ } } return arr; } console.log(countSort(ary));
Related tutorial recommendations:js tutorial
The above is the detailed content of How to implement counting sorting in js. For more information, please follow other related articles on the PHP Chinese website!