Home > Web Front-end > JS Tutorial > How to implement counting sorting in js

How to implement counting sorting in js

王林
Release: 2020-04-01 09:17:59
forward
2940 people have browsed it

How to implement counting sorting in js

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]
Copy after login

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));
Copy after login

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!

Related labels:
source:jb51.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template