算法描述

  1. 统计数组中每个值为 i 的元素出现的次数,存入统计数组 C 的第 i 项
  2. 依次将统计数组 C 中值 val 不为 0 的下标推入到结果数组,推入 val 次

动图演示

countingSort.gif

算法实现

  1. /**
  2. * 计数排序
  3. * @param {number[]} arr 数组
  4. */
  5. const countingSort = (arr) => {
  6. const count = []
  7. for (let i = 0; i < arr.length; i++) {
  8. if (!count[arr[i]]) count[arr[i]] = 0
  9. count[arr[i]] += 1
  10. }
  11. const result = []
  12. for (let i = 0; i < count.length; i++) {
  13. if (count[i]) {
  14. for (let j = 0; j < count[i]; j++) {
  15. result.push(i)
  16. }
  17. }
  18. }
  19. return result
  20. }

当输入 n 个 0~k 之间的整数时,时间复杂度为 o(n+k),空间复杂度为 o(n+k)