Sleep Sort in Scala

Published on 11 April 2026 (Updated: 11 April 2026)

Welcome to the Sleep Sort in Scala page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

import java.util.concurrent.{CountDownLatch, Executors}
import java.util.{ArrayList, Collections}
import scala.util.Try
import scala.jdk.CollectionConverters.*

object SleepSort:

  def main(args: Array[String]): Unit =
    args.toList match
      case raw :: Nil =>
        val numbers = parse(raw)
        if numbers.length < 2 then usage()
        println(format(sleepSort(numbers)))

      case _ =>
        usage()

  private def usage(): Nothing =
    println("""Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"""")
    sys.exit(1)

  private def parse(input: String): List[Int] =
    input
      .split(",")
      .iterator
      .map(_.trim)
      .filter(_.nonEmpty)
      .flatMap(s => Try(s.toInt).toOption)
      .toList match
        case Nil => usage()
        case xs  => xs

  private def format(xs: List[Int]): String =
    xs.mkString(", ")

  private def sleepSort(input: List[Int]): List[Int] =
    val sortedList =
      Collections.synchronizedList(new ArrayList[Int]())

    val executor = Executors.newCachedThreadPool()
    val latch = new CountDownLatch(input.size)

    input.foreach { n =>
      executor.submit(() =>
        try
          Thread.sleep(n.toLong * 100L)
          sortedList.add(n)
        catch
          case _: InterruptedException =>
            Thread.currentThread().interrupt()
        finally
          latch.countDown()
      )
    }

    latch.await()
    executor.shutdown()

    sortedList.asScala.toList

Sleep Sort in Scala was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.