Sleep-sort in javascript

Sleep sort is a joke sorting algorithm.
Sleep sort spawns off one process for each argument. Each process waits for n milliseconds, then prints out n, meaning it takes 1 millisecond to print out "1", 2 millisecond to print out "2", 100 millisecond to print out "100". This means that for the most part, the numbers are printed out in the order of their size, thus "sorting" the arguments.

The complexity of this algorithm in a perfect world is O(N).
In reality, the complexity is O(n^2 + max(args)), because maintaining multiple background processes relies on the operating system to manage the context switching and prioritisation of the processes, and so the algorithm basically outsources the actual sorting to the kernel.

const unorderedArray = [1,4,6,3,7,9]

const proms = unorderedArray.map(n => {  
   return new Promise((resolve, fail)=>{
      setTimeout(function(){
         resolve(n)
      },n)
   })
})

Promise.all(proms)  
.then(sortedArray => console.log(sortedArray))

Davide Andreazzini

Read more posts by this author.