桶排序的思路

桶排序

典型案例:arr1 [ 1, 2, 5, 2, 1, 8, 9, 5, 2, 8, 9, 10] 按照 arr2 [1, 5, 9, 8, 2, 10]的顺序排序

结果: [1,1,5,5,9,9,8,8,2,2,2,10]

思路:

function solution(arr1, arr2{
    const map = new Map(),
        len1 = arr1.length,
        len2 = arr2.length,
        res = []
    for (let i = 0; i < len2; i += 1) {
        map.set(arr2[i], [])
    }

    for (let i = 0; i < len1; i += 1) {
        const item = arr1[i]
        if (map.has(item)) {
          const temp = map.get(item)
          temp.push(item)
        }
    }

    map.forEach((value) => {
        res = res.concat(value)
    })

    return res
}

另一个有趣的例子, 知乎上看到的

const original = [3,1,15,2,9,6,3,2,7,1]
const result = []

original.forEach(n => setTimeout(() => result.push(n), n)

睡眠排序,感觉也像是桶排序,时间为桶,将元素按照时间进行排序

虽然这是一种'歪门',但是思路还是挺有意思的

posted @ 2020-07-26 17:17  rencoo  阅读(315)  评论(0编辑  收藏  举报