"Introduction to Algorithms" ʚReading Notes & Analysis ɞ Chapter 8-Cardinal Number Sorting (including js version code implementation)

What is radix sort

As shown in the figure below, we arrange the ones, tens, and hundreds in order, and then we can get a complete sorting process

Algorithm process

  1. Because each base can only be 0-9, it can be performed on each column计数排序
  2. Loop through all columns

Algorithm implementation

function createZero(num, targetLength) {
    
    
    let t = targetLength - num.toString().length
    let str = ''
    while (t > 0) {
    
    
        t--;
        str += '0'
    }
    return str + num.toString()
}

function RadixSort(arr) {
    
    
    let len = arr.length
    let max = Math.max.apply(null, arr)
    const targetLength = max.toString().length
    let strArr = arr.map(t => createZero(t,targetLength))
    let map = {
    
    }
    for (let j = targetLength - 1; j >= 0; j--) {
    
    
        for (let i = 0; i < len; i++) {
    
    
            map[Number(strArr[i][j])] ? map[Number(strArr[i][j])].push(strArr[i]) : map[Number(strArr[i][j])] = [strArr[i]]
        }
        let temp = [];
        for (let q = 0; q < 10; q++) {
    
    
            temp = map[q] ? temp.concat(map[q]) : temp
        }
        map = []
        strArr = temp
    }
    let result = strArr.map(s => Number(s))
    return result
}

module.exports = RadixSort

Guess you like

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