算法排序篇-6【计数排序】js解法

61 阅读1分钟

计数排序

基本思路

计数排序使用一个用来存储每个元素在数组中出现次数的临时数组。计数完成后,可得到新的排好序的数组。 它是一个整数排序算法。

实现逻辑

  1. 如果原数组长度小于等于1,则直接返回数组,不需要排序。
  2. 找到原数组中最大的值。(用来创建包含最大值个元素的数组)
  3. 创建一个元素数量为数组最大值的数组(新数组)。
  4. 遍历原数组,每个元素的值作为新数组的索引,如果该位置上没有值则初始化为0,如果该位置上有值,则递增数量。
  5. 遍历新数组,得到排好序的数组。

代码实现

let array = [3,1,5,2,4,6,8, 6, 6]
function countingSort(array) {
    if (array.length < 2) {
        return array
    }
    const maxValue = findMaxValue(array) // 寻找数组中的最大值
    const counts = new Array(maxValue + 1) // 生成一个包含(最大值+1)数量个元素的数组
    array.forEach(element => {
        if (!counts[element]) {
            counts[element] = 0 // 没有初始化的赋值0
        }
        counts[element]++ // 递增数组中值的数量
    });
    let sortedIndex = 0
    counts.forEach((count, i) => {
        while (count > 0) {
            array[sortedIndex++] = i // 递增把数据加入到数组中
            count-- // 可能存在多个同样的值,进行递减,为0则跳出循环
        }
    })
    return array
}

function findMaxValue(array) {
    let maxValue = array[0]
    for (let i = 0; i <= array.length; i++) {
        if(array[i] > maxValue) {
            maxValue = array[i]
        }
    }
    return maxValue
}
countingSort(array)

性能

技术排序时间复杂度为O(n+k),其中k是临时计数数组的大小。 它是用来排序整数的优秀算法,但是需要更多内存来存放临时数组。