Though am not a full-time coding geek, I never miss an opportunity to appreciate good algorihms and snippets. Saying that, now this post is about an invention of a sorting algorithm on 20th January, 2011 by someone “Anonymous” in the 4Chan Family. If you do not know about the 4Chan website, atleast you must know about the Operation Payback which they launched in 2010. I became a fan to 4Chan after that incident. Now here lets discuss a sorting algorithm from 4Chan which intrigued me. Its called the SleepSort. I know it sounds funny, but believe me you’re gonna feel great once you understand it. Here is the code..

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

filename : sort.bash
usage : bash sort.bash 5 2 8 1

The code is amazingly simple, but the algorithm is the interesting part.
while loop : The loop executes until there is a value for the “$1” expression, which actually denotes the command-line argument. So as long as there is a command-line argument value, the function “f” is called by f "$1" &. Because of the presence of “&”, the command is executed as a background process without disturbing the control flow in the current execution, and thus the next line shift is executed immediately. This line shifts the the focus on to the next command-line argument, and therefore now the value of “$1” is the next value in the argument list. This loop is repeated until all the command-line arguments are exhausted. After the loop is done with, there is a separate background process executing the function “f” corresponding to each command-line argument.
function f() : This function makes the process to sleep for “$1” number of seconds and then prints the value of “$1” in the terminal by the echo command. We know that all the background processes we created have a value from the argument-list. Thus lower the value of the argument, earlier is its value displayed on the screen. Like 1 is displayed after 1 second, and 3 is displayed after 3 seconds. Thus the numbers are printed in ascending order.
Though there is a major drawback that higher argument values lead to increased delay in getting the result, still the algorithm amused me.
Happy Hacking 🙂
Advertisements