"Introduction to Algorithms" @书Note@ Chapter 8-Counting and Sorting (including js version code implementation)

What is count sort

Counting sorting is a bit similar to the taste of exhaustion, we record the number of times each number in the number appears and finally just combine them in turn. For example, if the figure 9 appears twice, put two 9s in the array

Algorithm process

  1. Get the maximum value in the array
  2. Sort them and record the number of times each number appears
  3. Rearrange the output array

Algorithm implementation

function CountingSort(arr) {
    
    
    let len = arr.length;
    let max = Math.max.apply(null, arr);
    let temp = new Array(max + 1).fill(null);
    let result = [];
    for (let i = 0; i < len; i++) {
    
    
        temp[arr[i]] = temp[arr[i]] ? temp[arr[i]] + 1 : 1
    }
    temp.forEach((e, index) => {
    
    
        if (e != null) {
    
    
            for (let i = 0; i < e; i++) {
    
    
                result.push(index)
            }
        }
    })
    return result
}
module.exports = CountingSort

Guess you like

Origin blog.csdn.net/weixin_38616850/article/details/110926323