Sleep sort algorithm

A while ago, one of my friends Simon told me about a funny sorting algorithm called sleep sort (originaly posted on 4chan).

The idea behind it is really simple: you sleep for the value of each number in the array and then you add that integer to the end of the array. Of course you can use some kind of constant (in my example I divided by 1000) to reduce the sleep time significantly.

He wrote an asynchronous javascript implementation of this algorithm - I could not resist to write a Ruby one. Here is my take.

def sleep_sort(*args)
  args.each { |e| fork { sleep(e.to_f/1000); puts e } }
end
sleep_sort(*ARGV) # Outputs to stdout

While this is great, I think it would be much more cleaner to extend Array directly, as following:

class Array
  def sleep_sort
    [].tap { |a| self.map { |e| 
      Thread.new{ sleep e.to_f/1000; a << e} }.each{ |t| 
        t.join
        } 
      }
  end
end

puts ARGV.sleep_sort

Sleep sort is not really a linear sorting algorithm. It kind of depends on how many cores you have, or on how many threads you can run simultaneously.

I really like this kind of esoteric algorithm - this could lead to great discussions about algorithms, operating sytems and computer architecture.