Back to blog
Dec 2023
3 min read

Sleep Sort

Funny little sorting algorithm

I was recently going through different sorting algorithms and their respective complexities when I came across a rather ineffective yet funny sorting technique: Sleep Sort. So, obviously, I thought of sharing it here.

Sleep Sort works by creating a separate thread for each number in the array. Each thread goes to sleep for an amount of time proportional to the number it represents. When a thread wakes up, its number is then recorded/printed. Essentially, the smaller numbers wake up and get sorted first because they sleep for less time. ⏰

But don’t worry, Sleep Sort isn’t meant to be taken too seriously. It emerged more as a humorous take on sorting algorithms, showcasing a creative yet impractical use of threads and sleep functions. It might not drastically change how we sort data, but it definitely adds a bit of fun to the learning process!

Here’s a fun implementation of Sleep Sort in Bash:

#!/bin/bash

function sleep_sort() {
    # For each number passed as argument
    for i in "$@"; do
        # Start a background process for each number
        (sleep "$i" && echo "$i") &
    done
    # Wait for all background processes to finish
    wait
}

When you run this script, it will create a separate process for each number. Each process will sleep for a number of seconds equal to the value it’s sorting, then print the number when it wakes up. The output will show the numbers in ascending order!

Note: This is obviously not practical for real-world use as:

  1. It’s extremely inefficient (imagine sorting numbers in thousands!)
  2. It only works for positive integers
  3. The accuracy depends on the system’s process scheduling
  4. The time complexity is literally the largest number in your input 😄

But hey, it’s a fun way to learn about parallel processing and bash scripting! 🚀