SoFunction
Updated on 2025-03-02

Example of implementation of js count sorting (upgraded version)

Original count sorting, the volume of the bucket requires a number that can contain the minimum value to the maximum value. Here we can replace the bucket with an object, using the two characteristics of automatic sorting of the object and the key-value pairs that cannot appear with the same attribute name. There is no need for a bucket with an ordered volume, 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]

function countSort(arr){
  let obj={};
  //Transf the original array and add a key-value pair to the object. If it already exists, the corresponding attribute value ++. If it does not exist, add a key-value pair.  for(let i=0;i<;i++){
    if(!obj[arr[i]]){
      obj[arr[i]]=1;
    }else{
      obj[arr[i]]++;
    } 
    }
  let index=0;
  //Transfer the object attribute name and put it back in order to overwrite the original array  for(let key in obj){
    while(obj[key]>0){
      arr[index]=Number(key);
      obj[key]--;
      index++
    }
  }
  return arr;
}

(countSort(ary));

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.