小编Sea*_*ang的帖子

Javascript 计数排序实现

这是在 Javascript 中实现计数排序的好方法还是最佳方法?找不到标准的 JS 计数排序示例。

function countingSort(arr){
  var helper = []; // This helper will note how many times each number appeared in the arr
                   // Since JS arrary is an object and elements are not continuously stored, helper's Space Complexity minor that n
  for(var i = 0; i<arr.length; i++){
    if(!helper[arr[i]]){
        helper[arr[i]] = 1;
    }else{
        helper[arr[i]] += 1;
    }
  }

  var newArr = []; 
  for(i in helper){
    while(helper[i]>0){
        newArr.push(parseInt(i));
        helper[i]--;
    }
  }
  return newArr; 
}

var arr = [5,4,3,2,1,0];
console.log(countingSort(arr)); …
Run Code Online (Sandbox Code Playgroud)

javascript algorithm counting-sort

4
推荐指数
1
解决办法
7365
查看次数

标签 统计

algorithm ×1

counting-sort ×1

javascript ×1