Tag Archives: code snippet

Sleep Sort

I may be late to the party here, but I was introduced to the Sleep Sort algorithm at Sync Conf last week. The code is deceptively simple:

#!/bin/bash
function f() {
    sleep "$1"
    echo "$1"
}
while [ -n "$1" ]
do
    f "$1" &
    shift
done
wait

Of course it’s also hideously inefficient. Using it to sort 3 1 4 1 5 is fine as it only takes 5 seconds, but I wouldn’t like to sort any number much over 10 as you could be there for some time. Does make me wonder if you could speed it up by using milliseconds rather than seconds… and at what point you start getting race conditions.