Bash: Sleepsort Algorithm

Some code that a friend showed to me was this:

#!/bin/bash

function f() {
  sleep "$1"
  echo "$1"
}

while [ -n "$1" ]
do
  f "$1" &
  shift
done

wait

Example:

./sleepsort 9 3 7 1 3 2 4 7 4 6

He called it "sleepsort". And somehow, it really works. Not the fastest, but it works.

Related posts:


 
 
 

3 Kommentare zu “Bash: Sleepsort Algorithm”

  1. Chris Devers 15. Juni 2011 um 20:00

    The results seem to be amusingly non-deterministic with non-numeric input:

    $ for i in 1 2 3 4 5; do ./sleepsort a 1 c 3 2 b | fmt; done
    a c b 1 2 3
    c a b 1 2 3
    a b c 1 2 3
    a c b 1 2 3
    a c b 1 2 3
    $

  2. Stefan Mark 16. Juni 2011 um 15:50

    What do you mean, "not the fastest"? This algorithm actually achieves O(n) complexity ;)

  3. Julius 17. Juni 2011 um 08:28

    Yeah, good find columbo ;)