美文网首页
JavaScript-计数排序

JavaScript-计数排序

作者: Shaw007 | 来源:发表于2018-08-03 15:56 被阅读0次

前言

计数排序是利用hash的数据结构,即key-value,以值为key,出现次数为其value。

相对于比较排序(最优复杂度为nlogn), 计数排序复杂度为O(n+max)

适用

不适用于负数及小数,并消耗较大的空间,特别是数据特别分散时。

JS实现

Array.prototype.countSort = function() {
  const C = []
  for(let i = 0; i < this.length; i++) {
    const j = this[i]
    C[j] >= 1 ? C[j] ++ : (C[j] = 1)
  }
  const D = []
  for(let j = 0; j < C.length; j++) {
    if(C[j]) {
      while(C[j] > 0) {
        D.push(j)
        C[j]--
      }
    }
  }
  return D
}

上述中,若是D通过寻找C中最大值作为循环结束,则要注意循环结束条件是<=.

相关文章

网友评论

      本文标题:JavaScript-计数排序

      本文链接:https://www.haomeiwen.com/subject/clxuvftx.html