How to resolve the algorithm Sorting algorithms/Sleep sort step by step in the Elixir programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sorting algorithms/Sleep sort step by step in the Elixir programming language

Table of Contents

Problem Statement

In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sorting algorithms/Sleep sort step by step in the Elixir programming language

Source code in the elixir programming language

defmodule Sort do
  def sleep_sort(args) do
    Enum.each(args, fn(arg) -> Process.send_after(self, arg, 5 * arg) end)
    loop(length(args))
  end
  
  defp loop(0), do: :ok
  defp loop(n) do
    receive do
        num -> IO.puts num
               loop(n - 1)
    end
  end
end

Sort.sleep_sort [2, 4, 8, 12, 35, 2, 12, 1]


  

You may also check:How to resolve the algorithm Literals/Integer step by step in the Seed7 programming language
You may also check:How to resolve the algorithm Loops/Break step by step in the REBOL programming language
You may also check:How to resolve the algorithm Sorting algorithms/Heapsort step by step in the REXX programming language
You may also check:How to resolve the algorithm Sierpinski arrowhead curve step by step in the Perl programming language
You may also check:How to resolve the algorithm GSTrans string conversion step by step in the Python programming language