JavaScript/CoffeeScript sleepsort

, posted

I came across the sleepsort today, which is a humorous sorting algorithm. Basically, it sleeps for n milliseconds, where n is each number. Smaller numbers will only sleep briefly and larger ones will sleep longer, so it outputs in the right order!

I was “inspired” and implemented it in JavaScript:

function sleepsort() {
  var i = arguments.length;
  while (i--) {
      function (n) {

I also implemented it in CoffeeScript:

sleepsort = ->
  setTimeout ((n) => console.log n), number, number for number in arguments

Perhaps it’s obvious that it’s not a “real” sort. It’s clearly very slow for large numbers and doesn’t even work for negative numbers. Still a fun little exercise!