pwstrick / daily

一份搜集的前端面试题目清单、面试相关以及各类学习的资料(不局限于前端)
2.39k stars 242 forks source link

计数排序 #990

Open pwstrick opened 4 years ago

pwstrick commented 4 years ago
function countingSort(arr) {
  var count = arr.length,
    countArr = [];
  if (count <= 1)
    return arr;
  var min = Math.min.apply(null, arr),  //取出最小值
    max = Math.max.apply(null, arr);    //取出最大值
  for (var i = min; i <= max; i++) {
    countArr[i] = 0;
  }
  arr.forEach(function (value, key) {
    countArr[value] = countArr[value] + 1;
  });

  var list = [];
  //value是每个元素出现的次数
  countArr.forEach(function (value, key) {
    for (var i = 0; i < value; i++) {
      list.push(key);
    }
  });
  return list;
}