睡眠排序

先上代码:

const A = [3, 1, 2, 5, 4, 0, 10]
const res = []
A.forEach(n => setTimeout(() => res.push(n), n*10))
setTimeout(function(){console.log(res)}, 1000)

原理其实也很简单,相当于同时启动多个定时器,每个定时器结束后就将它push到res数组。

由于0ms、1ms、2ms这些差距很小,结果可能不稳定,乘了一个权重10;同理,如果数字很大,也可以进行取对数等操作。

输出结果时,由于是异步的,也需要延时输出。

参考链接:https://www.zhihu.com/question/358255792/answer/969450646

原文地址:https://www.cnblogs.com/lfri/p/12194983.html