Sorting algorithms/Sleep sort: Difference between revisions

m
(Remove unnecessary file extension in Raku's reactive programming example)
 
(30 intermediate revisions by 23 users not shown)
Line 1:
{{task|Sorting Algorithms}}{{Sorting Algorithm}}
{{Sorting Algorithm}}
[[Category:Sorting]]
 
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.
 
Line 7 ⟶ 10:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Ada.Command_Line; use Ada.Command_Line;
procedure SleepSort is
Line 21 ⟶ 24:
TaskList(i) := new PrintTask(Integer'Value(Argument(i)));
end loop;
end SleepSort;</langsyntaxhighlight>
{{out}}
<pre>./sleepsort 35 21 11 1 2 27 32 7 42 20 50 42 25 41 43 14 46 20 30 8
Line 27 ⟶ 30:
 
=={{header|APL}}==
<syntaxhighlight lang="apl">
<lang APL>
sleepsort←{{r}⎕TSYNC{r,←⊃⍵,⎕DL ⍵}&¨⍵,r←⍬}
</syntaxhighlight>
</lang>
 
=={{header|Assembly}}==
{{works with|flat assembler for Linux x64}}
<syntaxhighlight lang="asm">
format ELF64 executable 3
entry start
 
; parameters: argc, argv[] on stack
start:
mov r12, [rsp] ; get argc
mov r13, 1 ; skip argv[0]
 
.getargv:
cmp r13, r12 ; check completion of args
je .wait
mov rdi, [rsp+8+8*r13] ; get argv[n]
inc r13
 
mov rax, 57 ; sys_fork
syscall
 
cmp rax, 0 ; continue loop in main process
jnz .getargv
 
push rdi ; save pointer to sort item text
 
call atoi_simple ; convert text to integer
test rax, rax ; throw out bad input
js .done
 
sub rsp, 16 ; stack space for timespec
mov [rsp], rax ; seconds
mov qword [rsp+8], 0 ; nanoseconds
 
lea rdi, [rsp]
xor rsi, rsi
mov rax, 35 ; sys_nanosleep
syscall
 
add rsp, 16
 
pop rdi ; retrieve item text
call strlen_simple
 
mov rsi, rdi
mov byte [rsi+rax], ' '
mov rdi, 1
mov rdx, rax
inc rdx
mov rax, 1 ; sys_write
syscall
 
jmp .done
 
.wait:
dec r12 ; wait for each child process
jz .done
mov rdi, 0 ; any pid
mov rsi, 0
mov rdx, 0
mov r10, 4 ; that has terminated
mov rax, 247 ; sys_waitid
syscall
 
jmp .wait
 
.done:
xor rdi, rdi
mov rax, 60 ; sys_exit
syscall
 
; parameter: rdi = string pointer
; return: rax = integer conversion
atoi_simple:
push rdi
push rsi
 
xor rax, rax
 
.convert:
movzx rsi, byte [rdi]
test rsi, rsi ; check for null
jz .done
 
cmp rsi, '0'
jl .baddigit
cmp rsi, '9'
jg .baddigit
sub rsi, 48 ; get ascii code for digit
 
imul rax, 10 ; radix 10
add rax, rsi ; add current digit to total
 
inc rdi
jmp .convert
 
.baddigit:
mov rax, -1 ; return error code on failed conversion
 
.done:
pop rsi
pop rdi
ret ; return integer value
 
; parameter: rdi = string pointer
; return: rax = length
strlen_simple:
xor rax, rax
 
.compare:
cmp byte [rdi+rax], 0
je .done
inc rax
jmp .compare
 
.done:
ret
</syntaxhighlight>
{{out}}
<pre>
./sleepsort 35 21 11 1 2 27 32 7 42 20 50 42 25 41 43 14 46 20 30 8
1 2 7 8 11 14 20 20 21 25 27 30 32 35 41 42 42 43 46 50
</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">items := [1,5,4,9,3,4]
for i, v in SleepSort(items)
result .= v ", "
MsgBox, 262144, , % result := "[" Trim(result, ", ") "]"
return
 
SleepSort(items){
global Sorted := []
slp := 50
for i, v in items{
fn := Func("PushFn").Bind(v)
SetTimer, %fn%, % v * -slp
}
Sleep % Max(items*) * slp
return Sorted
}
 
PushFn(v){
global Sorted
Sorted.Push(v)
}</syntaxhighlight>
{{out}}
<pre>[1, 3, 4, 4, 5, 9]</pre>
 
=={{header|Bash}}==
<langsyntaxhighlight lang="bash">
function sleep_and_echo {
sleep "$1"
Line 43 ⟶ 194:
 
wait
</syntaxhighlight>
</lang>
 
{{out}}
Line 74 ⟶ 225:
{{works with|BBC BASIC for Windows}}
This does not explicitly 'sleep', but uses timers to implement the different delays.
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"TIMERLIB"
DIM test%(9)
Line 97 ⟶ 248:
DEF PROCtask7 : PRINT test%(7) : ENDPROC
DEF PROCtask8 : PRINT test%(8) : ENDPROC
DEF PROCtask9 : PRINT test%(9) : ENDPROC</langsyntaxhighlight>
'''Output:'''
<pre>
Line 113 ⟶ 264:
 
=={{header|Brainf***}}==
<syntaxhighlight lang="c">
<lang C>
>>>>>,----------[++++++++
++[->+>+<<]>+>[-<<+>>]+++
Line 122 ⟶ 273:
->>>>>[>>>>>]<-<<<<[<<<<<
]+<]<<<<]>>>>>[>>>>>]<]
</syntaxhighlight>
</lang>
Not exactly 'sleep' sort but it is similar: it inputs an array of digits and in each iteration reduces elements by 1. When an element becomes 0 – it prints the original digit.
 
Line 130 ⟶ 281:
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
Line 142 ⟶ 293:
wait(0);
return 0;
}</langsyntaxhighlight>
Running it:<syntaxhighlight lang="text">% ./a.out 5 1 3 2 11 6 4
1
2
Line 150 ⟶ 301:
5
6
11</langsyntaxhighlight>
If you worry about time efficiency of this sorting algorithm (ha!), you can make it a 100 times faster by replacing the <code>sleep(...</code> with <code>usleep(10000 * (c = atoi(v[c])))</code>. The smaller the coefficient, the faster it is, but make sure it's not comparable to your kernel clock ticks or the wake up sequence will be wrong.
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 179 ⟶ 330:
SleepSort(arguments.Select(int.Parse));
}
}</langsyntaxhighlight>
 
===Using Tasks===
 
<langsyntaxhighlight lang="csharp">var input = new[] { 1, 9, 2, 1, 3 };
 
foreach (var n in input)
Line 191 ⟶ 342:
Console.WriteLine(n);
});
</syntaxhighlight>
</lang>
 
Output, i.e. in LINQPad:
Line 202 ⟶ 353:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <chrono>
#include <iostream>
Line 223 ⟶ 374:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 246 ⟶ 397:
=={{header|Clojure}}==
Using core.async
<langsyntaxhighlight lang="clojure">(ns sleepsort.core
(require [clojure.core.async :as async :refer [chan go <! <!! >! timeout]]))
 
Line 254 ⟶ 405:
(go (<! (timeout (* 1000 i)))
(>! c i)))
(<!! (async/into [] (async/take (count l) c)))))</langsyntaxhighlight>
<langsyntaxhighlight lang="clojure">(sleep-sort [4 5 3 1 2 7 6])
;=> [1 2 3 4 5 6 7]</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
{{works_with|node.js}}
<langsyntaxhighlight lang="coffeescript">
after = (s, f) -> setTimeout f, s*1000
 
Line 272 ⟶ 423:
input = (parseInt(arg) for arg in process.argv[2...])
sleep_sort input
</syntaxhighlight>
</lang>
output
<syntaxhighlight lang="text">
> time coffee sleep_sort.coffee 5, 1, 3, 4, 2
1
Line 285 ⟶ 436:
user 0m0.147s
sys 0m0.024s
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
{{works_with|SBCL}}
<langsyntaxhighlight lang="lisp">(defun sleeprint(n)
(sleep (/ n 10))
(format t "~a~%" n))
Line 296 ⟶ 447:
(sb-thread:make-thread (lambda() (sleeprint (parse-integer arg)))))
 
(loop while (not (null (cdr (sb-thread:list-all-threads)))))</langsyntaxhighlight>
{{Out}}
<pre>$ sbcl --script ss.cl 3 1 4 1 5
Line 307 ⟶ 458:
 
=={{header|D}}==
<syntaxhighlight lang="d">void main(string[] args)
<lang d>
import core.thread, std.concurrency, std.datetime,
std.stdio, std.algorithm, std.conv;
 
void main(string[] args)
{
import core.thread, std;
if (!args.length)
args.drop(1).map!(a => a.to!uint).parallel.each!((a)
return;
{
 
Thread.sleep(dur!"msecs"(a));
foreach (number; args[1 .. $].map!(to!uint))
spawnwrite((uinta, num" ") {;
});
Thread.sleep(dur!"msecs"(10 * num));
}</syntaxhighlight>
writef("%d ", num);
}, number);
 
thread_joinAll();
}
 
</lang>
{{out}}
<pre>$ ./sorting_algorithms_sleep_sort 200 20 50 10 80
<pre>sorting_algorithms_sleep_sort 1 6 2 5 3 4
110 220 350 480 5 6200</pre>
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">
void main() async {
Future<void> sleepsort(Iterable<int> input) => Future.wait(input
Line 338 ⟶ 479:
await sleepsort([3, 10, 2, 120, 122, 121, 54]);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 351 ⟶ 492:
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program SleepSortDemo;
 
{$APPTYPE CONSOLE}
Line 409 ⟶ 550:
Writeln;
ReadLn;
end.</langsyntaxhighlight>
Output:
<pre>
Line 417 ⟶ 558:
 
=={{header|Elena}}==
ELENA 56.0 :
<langsyntaxhighlight lang="elena">import extensions;
import system'routines;
import extensions'threading;
Line 429 ⟶ 570:
sleepSort()
{
self.forEach::(n)
{
threadControl.start(
Line 443 ⟶ 584:
}
}
 
public program()
{
program_arguments.skipping:(1).selectBy(mssgconst toInt<convertorOpintConvertOp>[1]).toArray().sleepSort();
 
console.readChar()
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Sort do
def sleep_sort(args) do
Enum.each(args, fn(arg) -> Process.send_after(self, arg, 5 * arg) end)
Line 468 ⟶ 609:
end
 
Sort.sleep_sort [2, 4, 8, 12, 35, 2, 12, 1]</langsyntaxhighlight>
 
{{out}}
Line 485 ⟶ 626:
GNU Emacs supports threads, but it's more straightforward to do this by just using timers.
Evaluate in the *scratch* buffer by typing <code>C-M-x</code> on the expression:
<langsyntaxhighlight Lisplang="lisp">(dolist (i '(3 1 4 1 5 92 65 3 5 89 79 3))
(run-with-timer (* i 0.001) nil 'message "%d" i))</langsyntaxhighlight>
 
The output printed in the *Messages* buffer is:
Line 501 ⟶ 642:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">#!/usr/bin/env escript
%% -*- erlang -*-
%%! -smp enable -sname sleepsort
Line 518 ⟶ 659:
io:format("~s~n", [Num]),
loop(N - 1)
end.</langsyntaxhighlight>
{{out}}
<pre>./sleepsort 2 4 8 12 35 2 12 1
Line 531 ⟶ 672:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">include get.e
 
integer count
Line 561 ⟶ 702:
task_yield()
end while
end if</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
let sleepSort (values: seq<int>) =
values
|> Seq.map (fun x -> async {
do! Async.Sleep x
Console.WriteLine x
})
|> Async.Parallel
|> Async.Ignore
|> Async.RunSynchronously
</syntaxhighlight>
 
Usage:
<syntaxhighlight lang="fsharp">
sleepSort [10; 33; 80; 32]
10
32
33
80
</syntaxhighlight>
 
=={{header|Factor}}==
 
<syntaxhighlight lang="factor">
<lang Factor>
USING: threads calendar concurrency.combinators ;
 
: sleep-sort ( seq -- ) [ dup seconds sleep . ] parallel-each ;
</syntaxhighlight>
</lang>
 
Usage:
 
<syntaxhighlight lang="factor">
<lang Factor>
{ 1 9 2 6 3 4 5 8 7 0 } sleep-sort
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
<syntaxhighlight lang="fortran">
<lang Fortran>
program sleepSort
use omp_lib
Line 612 ⟶ 775:
end subroutine sleepNprint
end program sleepSort
</syntaxhighlight>
</lang>
Compile and Output:
<pre>
Line 629 ⟶ 792:
Can't use FreeBASIC '''sleep''' since it halts the program.
Instead it uses a second array filled with times based on the value of number, this array is check against the timer. If the timer is past the stored time the value is printed.
<langsyntaxhighlight lang="freebasic">' version 21-10-2016
' compile with: fbc -s console
' compile with: fbc -s console -exx (for bondry check on the array's)
Line 686 ⟶ 849:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>unsorted 5 2 5 6 4 6 9 5 1 2 0
Line 693 ⟶ 856:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 718 ⟶ 881:
fmt.Println(<-out)
}
}</langsyntaxhighlight>
Usage and output:
<pre>./sleepsort 3 1 4 1 5 9
Line 728 ⟶ 891:
9
</pre>
 
=== Using sync.WaitGroup ===
<syntaxhighlight lang="go">package main
 
import (
"fmt"
"log"
"os"
"strconv"
"sync"
"time"
)
 
func main() {
var wg sync.WaitGroup
wg.Add(len(os.Args[1:]))
for _,i := range os.Args[1:] {
x, err := strconv.ParseUint(i, 10, 64)
if err != nil {
log.Println(err)
}
wg.Add(1)
go func(i uint64, wg *sync.WaitGroup) {
defer wg.Done()
time.Sleep(time.Duration(i) * time.Second)
fmt.Println(i)
}(x, &wg)
}
wg.Wait()
}</syntaxhighlight>
 
Usage and output are the same as the version using channels. Note that the original version would sleep for increments of 1 full second, so I made my code do the same.
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">
@Grab(group = 'org.codehaus.gpars', module = 'gpars', version = '1.2.1')
import groovyx.gpars.GParsPool
Line 740 ⟶ 935:
}
}
</syntaxhighlight>
</lang>
 
Sample Run:
Line 753 ⟶ 948:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">import System.Environment
import Control.Concurrent
import Control.Monad
Line 764 ⟶ 959:
 
main :: IO ()
main = getArgs >>= sleepSort . map read</langsyntaxhighlight>
 
===Using mapConcurrentlymapConcurrently_===
<langsyntaxhighlight lang="haskell">import System.Environment
import Control.Concurrent
import Control.Concurrent.Async
 
sleepSort :: [Int] -> IO ()
sleepSort = (() <$) . mapConcurrentlymapConcurrently_ (\x -> threadDelay (x*10^4) >> print x)
 
main :: IO ()
main = getArgs >>= sleepSort . map read</langsyntaxhighlight>
 
This is problematic for inputs with multiple duplicates like <code>[1,2,3,1,4,1,5,1]</code> because simultaneous <code>print</code>s are done concurrently and the 1s and newlines get output in jumbled up order. The channels-based version above doesn't have this problem.
Line 783 ⟶ 978:
The following solution only works in Unicon.
 
<langsyntaxhighlight lang="unicon">procedure main(A)
every insert(t:=set(),mkThread(t,!A))
every spawn(!t) # start threads as closely grouped as possible
Line 791 ⟶ 986:
procedure mkThread(t,n) # 10ms delay scale factor
return create (delay(n*10),delete(t,&current),n@>&main)
end</langsyntaxhighlight>
 
Sample run:
Line 807 ⟶ 1,002:
->
</pre>
 
=={{header|J}}==
 
{{works with|J|903+}}
<syntaxhighlight lang="j">scheduledumb=: {{
id=:'dumb',":x:6!:9''
wd 'pc ',id
(t)=: u {{u y[erase n}} t=. id,'_timer'
wd 'ptimer ',":n p.y
}}
 
 
ssort=: {{
R=: ''
poly=. 1,>./ y
poly{{ y{{R=:R,m[y}}scheduledumb m y}}"0 y
{{echo R}} scheduledumb poly"0 >:>./ y
EMPTY
}}</syntaxhighlight>
 
Task example:
 
<syntaxhighlight lang="j"> t=: ?~30
t
11 7 22 16 17 2 1 19 23 29 9 21 15 10 12 27 3 4 24 20 14 5 26 18 8 6 0 13 25 28
ssort t
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29</syntaxhighlight>
 
Note that since t is the result of an RNG, the order of values in t would be different in subsequent attempts. For example:
 
<syntaxhighlight lang="j"> t=: ?~30
t
23 26 24 25 10 12 4 5 7 27 16 17 14 8 3 15 18 13 19 21 2 28 22 9 6 20 11 1 29 0
ssort t
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29</syntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">import java.util.concurrent.CountDownLatch;
 
public class SleepSort {
Line 840 ⟶ 1,070:
sleepSortAndPrint(nums);
}
}</langsyntaxhighlight>
Output (using "3 1 4 5 2 3 1 6 1 3 2 5 4 6" as arguments):
<pre>1
Line 858 ⟶ 1,088:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">Array.prototype.timeoutSort = function (f) {
this.forEach(function (n) {
setTimeout(function () { f(n) }, 5 * n)
});
}
</syntaxhighlight>
</lang>
Usage and output:
<langsyntaxhighlight lang="javascript">[1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0].timeoutSort(function(n) { document.write(n + '<br>'); })</langsyntaxhighlight>
<pre>
0
Line 879 ⟶ 1,109:
</pre>
 
<langsyntaxhighlight lang="javascript">Array.prototype.sleepSort = function(callback) {
const res = [];
for (let n of this)
Line 892 ⟶ 1,122:
[1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0].sleepSort(console.log);
// [ 1, 0, 2, 3, 4, 5, 5, 6, 7, 8, 9 ]
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
Line 899 ⟶ 1,129:
Doesn't actually sleep. Instead, iterates reducing the values by one until each is zero.
 
<langsyntaxhighlight lang="jq">echo '[5, 1, 3, 2, 11, 6, 4]' | jq '
def f:
if .unsorted == [] then
Line 909 ⟶ 1,139:
end;
{unsorted: [.[] | {v: ., t: .}], sorted: []} | f | .[]
'</langsyntaxhighlight>
{{out}}
<pre>1
Line 920 ⟶ 1,150:
 
=={{header|Julia}}==
{{works with|Julia|01.6}}
 
<langsyntaxhighlight lang="julia">function sleepsort(arrV::Vector{T}) where {T <: Real})
outU = Vector{eltype(arr)T}(0)
sizehint!(outU, length(arrV))
@sync for xv in arrV
@async begin
sleep(xabs(v))
(v < 0 ? pushfirst! : push!)(outU, xv)
end
end
return outU
end
 
 
 
v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", sleepsort(v))</langsyntaxhighlight>
 
{{out}}
<pre># unordered: [910, 5-1, 3, 8-9, 81, 2-5, 5-8, 2-7, 5-3, 53]
-> ordered: [2-9, 2-8, 3-7, -5, 5-3, 5-1, 51, 83, 83, 910]</pre>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.51
 
import kotlin.concurrent.thread
Line 964 ⟶ 1,196:
println("Unsorted: ${list.joinToString(" ")}")
sleepSort(list, 50)
}</langsyntaxhighlight>
 
Sample output:
<pre>
$ java -jar sleepsort.jar 5 7 -1 2 4 1 8 0 3 9 6
Unsorted: 5 7 2 4 1 8 0 3 9 6
Sorted : 0 1 2 3 4 5 6 7 8 9
</pre>
 
=== Using coroutines ===
<syntaxhighlight lang="kotlin">
import kotlinx.coroutines.*
 
fun sleepSort(list: List<Int>, delta: Long) {
runBlocking {
list.onEach {
launch {
delay(it * delta)
print("$it ")
}
}
}
}
 
fun main() {
val list = listOf(5, 7, 2, 4, 1, 8, 0, 3, 9, 6)
println("Unsorted: ${list.joinToString(" ")}")
print("Sorted : ")
sleepSort(list, 10)
}
 
</syntaxhighlight>
 
Output:
<pre>
Unsorted: 5 7 2 4 1 8 0 3 9 6
Sorted : 0 1 2 3 4 5 6 7 8 9
Line 976 ⟶ 1,238:
Here's a slow implementation using only stock C Lua:
 
<langsyntaxhighlight lang="lua">function sleeprint(n)
local t0 = os.time()
while os.time() - t0 <= n do
Line 1,002 ⟶ 1,264:
end
end
end</langsyntaxhighlight>
 
By installing LuaSocket, you can get better than 1-second precision on the clock, and therefore faster output:
 
<langsyntaxhighlight lang="lua">socket = require 'socket'
 
function sleeprint(n)
Line 1,034 ⟶ 1,296:
end
end
end</langsyntaxhighlight>
 
Either way, the output is the same:
Line 1,054 ⟶ 1,316:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">SleepSort = RunScheduledTask[Print@#, {#, 1}] & /@ # &;
SleepSort@{1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0};</langsyntaxhighlight>
{{Out}}
<pre>
Line 1,074 ⟶ 1,336:
As implemented this sample goes beyond the scope of the task as defined; it will handle negative numbers.
 
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
import java.util.concurrent.CountDownLatch
Line 1,133 ⟶ 1,395:
parent.getDoneLatch().countDown() -- this one's done; decrement the latch
return
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 1,142 ⟶ 1,404:
=={{header|Nim}}==
Compile with <code>nim --threads:on c sleepsort</code>:
<langsyntaxhighlight lang="nim">import os, strutils
 
proc single(n: int) =
Line 1,154 ⟶ 1,416:
thr.joinThreads
 
main()</langsyntaxhighlight>
Usage:
<pre>$ ./sleepsort 5 1 3 2 11 6 4
Line 1,166 ⟶ 1,428:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
use System.Concurrency;
use Collection;
Line 1,198 ⟶ 1,460:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
int main(int argc, char **argv)
Line 1,214 ⟶ 1,476:
}
[queue waitUntilAllOperationsAreFinished];
}</langsyntaxhighlight>
Rather than having multiple operations that sleep, we could also dispatch the tasks after a delay:
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
int main(int argc, char **argv)
Line 1,226 ⟶ 1,488:
^{ NSLog(@"%d\n", i); });
}
}</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 1,234 ⟶ 1,496:
20 milliseconds is used to (try to) handle scheduler tick on Windows systems (around 15 ms). On Linux systems (after kernel 2.6.8), this value can be smaller.
 
<langsyntaxhighlight Oforthlang="oforth">import: parallel
 
: sleepSort(l)
Line 1,240 ⟶ 1,502:
Channel new ->ch
l forEach: n [ #[ n dup 20 * sleep ch send drop ] & ]
ListBuffer newSize(l size) #[ ch receive over add ] times(l size) ;</langsyntaxhighlight>
 
{{out}}
Line 1,255 ⟶ 1,517:
3, 93, 94, 94, 95, 95, 96, 96, 97, 97, 98, 98, 99, 99, 100, 100]
</pre>
 
=={{header|Ol}}==
<syntaxhighlight lang="scheme">
(define (sleep-sort lst)
(for-each (lambda (timeout)
(async (lambda ()
(sleep timeout)
(print timeout))))
lst))
 
(sleep-sort '(5 8 2 7 9 10 5))
</syntaxhighlight>
{{Out}}
<pre>
2
5
5
7
8
9
10
</pre>
 
=={{header|Pascal}}==
{{works with|Free Pascal}}
my limit under linux was 4000 threads nearly 2 GB.
<syntaxhighlight lang="pascal">
program sleepsort;
{$IFDEF FPC}
{$MODE DELPHI} {$Optimization ON,ALL}
{$ElSE}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
SysUtils;
 
const
HiLimit = 40;
type
tCombineForOneThread = record
cft_count : Uint64;
cft_ThreadID: NativeUint;
cft_ThreadHandle: NativeUint;
end;
pThreadBlock = ^tCombineForOneThread;
var
SortIdx : array of INteger;
ThreadBlocks : array of tCombineForOneThread;
gblThreadCount,
Finished: Uint32;
 
procedure PrepareThreads(thdCount:NativeInt);
var
i : NativeInt;
Begin
For i := 0 to thdCount-1 do
ThreadBlocks[i].cft_count:= random(2*HiLimit);
end;
 
procedure TestRunThd(parameter: pointer);
var
pThdBlk: pThreadBlock;
fi: NativeInt;
begin
pThdBlk := @ThreadBlocks[NativeUint(parameter)];
with pThdBlk^ do
begin
sleep(40*cft_count+1);
fi := Finished-1;
//write(fi:5,cft_count:8,#13);
InterLockedDecrement(Finished);
SortIdx[fi]:= NativeUint(parameter);
end;
EndThread(0);
end;
 
procedure Test;
var
j,UsedThreads: NativeInt;
begin
randomize;
UsedThreads:= GblThreadCount;
Finished :=UsedThreads;
PrepareThreads(UsedThreads);
j := 0;
while (j < UsedThreads) do
begin
with ThreadBlocks[j] do
begin
cft_ThreadHandle :=
BeginThread(@TestRunThd, Pointer(j), cft_ThreadID,16384 {stacksize} );
If cft_ThreadHandle = 0 then break;
end;
Inc(j);
end;
writeln(j);
UsedThreads := j;
Finished :=UsedThreads;
repeat
sleep(1);
until finished = 0;
For j := 0 to UsedThreads-1 do
CloseThread(ThreadBlocks[j].cft_ThreadID);
 
//output of sleep-sorted data
For j := UsedThreads-1 downto 1 do
write(ThreadBlocks[SortIdx[j]].cft_count,',');
writeln(ThreadBlocks[SortIdx[0]].cft_count);
end;
 
 
begin
randomize;
gblThreadCount := Hilimit;
Writeln('Testthreads : ',gblThreadCount);
setlength(ThreadBlocks,gblThreadCount);
setlength(SortIdx,gblThreadCount);
Test;
 
setlength(ThreadBlocks, 0);
{$IFDEF WINDOWS}
readln;
{$ENDIF}
end.</syntaxhighlight>
{{out}}
<pre>time ./sleepsort
Testthreads : 40
40
1,8,9,10,11,12,12,13,14,18,24,24,24,26,28,35,35,37,42,49,50,52,54,54,56,57,59,60,61,62,64,69,69,71,72,73,76,77,78,79
 
real 0m3,164s</pre>
 
=={{header|Perl}}==
Basically the C code.
<langsyntaxhighlight Perllang="perl">1 while ($_ = shift and @ARGV and !fork);
sleep $_;
print "$_\n";
wait;</langsyntaxhighlight>
 
 
A more optimal solution makes use of Coro, a cooperative threading library. It has the added effect of being much faster, fully deterministic (sleep is not exact), and it allows you to easily collect the return value:
<langsyntaxhighlight Perllang="perl">use Coro;
$ret = Coro::Channel->new;
@nums = qw(1 32 2 59 2 39 43 15 8 9 12 9 11);
Line 1,276 ⟶ 1,672:
}
 
print $ret->get,"\n" for 1..@nums;</langsyntaxhighlight>
 
=={{header|Phix}}==
CopyBased ofon [[Sorting_algorithms/Sleep_sort#Euphoria|Euphoria]]
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>integer count
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (multitasking)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">count</span>
procedure sleeper(integer key)
? key
<span style="color: #008080;">procedure</span> <span style="color: #000000;">sleeper</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">)</span>
count -= 1
<span style="color: #0000FF;">?</span> <span style="color: #000000;">key</span> <span style="color: #000080;font-style:italic;">-- (or maybe res &= key)</span>
end procedure
<span style="color: #000000;">count</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
sequence s, val
atom task
<span style="color: #000080;font-style:italic;">--sequence s = command_line()[3..$]</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"3 1 4 1 5 9 2 6 5"</span><span style="color: #0000FF;">)</span>
s = command_line()
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
s = s[3..$]
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Nothing to sort.\n"</span><span style="color: #0000FF;">)</span>
if length(s)=0 then
<span style="color: #008080;">else</span>
puts(1,"Nothing to sort.\n")
<span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
else
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
count = 0
<span style="color: #004080;">object</span> <span style="color: #000000;">si</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">to_number</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
for i = 1 to length(s) do
<span style="color: #008080;">if</span> <span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">si</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
val = value(s[i])
<span style="color: #004080;">atom</span> <span style="color: #000000;">task</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">task_create</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sleeper</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">si</span><span style="color: #0000FF;">})</span>
if val[1] = GET_SUCCESS then
<span style="color: #7060A8;">task_schedule</span><span style="color: #0000FF;">(</span><span style="color: #000000;">task</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">si</span><span style="color: #0000FF;">/</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">si</span><span style="color: #0000FF;">/</span><span style="color: #000000;">10</span><span style="color: #0000FF;">})</span>
task = task_create(routine_id("sleeper"),{val[2]})
<span style="color: #000000;">count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
task_schedule(task,{val[2],val[2]}/10)
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
count += 1
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end if
end for
<span style="color: #008080;">while</span> <span style="color: #000000;">count</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">task_yield</span><span style="color: #0000FF;">()</span>
while count do
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
task_yield()
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<!--</syntaxhighlight>-->
end if</lang>
 
=={{header|PHP}}==
A PHP implementation of sleep sort using process forking.
<syntaxhighlight lang="php">
<?php
 
$buffer = 1;
$pids = [];
 
for ($i = 1; $i < $argc; $i++) {
$pid = pcntl_fork();
if ($pid < 0) {
die("failed to start child process");
}
 
if ($pid === 0) {
sleep($argv[$i] + $buffer);
echo $argv[$i] . "\n";
exit();
}
$pids[] = $pid;
}
 
foreach ($pids as $pid) {
pcntl_waitpid($pid, $status);
}
</syntaxhighlight>
<pre>
php ./sleepsort.php 35 21 11 1 2 27 32 7 42 20 50 42 25 41 43 14 46 20 30 8
1
2
7
8
11
14
20
20
21
25
27
30
32
35
41
42
42
43
46
50
</pre>
 
 
=={{header|PicoLisp}}==
===Sleeping in main process===
<langsyntaxhighlight PicoLisplang="picolisp">(de sleepSort (Lst)
(make
(for (I . N) Lst
Line 1,319 ⟶ 1,767:
(pop 'Lst)
(task (- I)) ) )
(wait NIL (not Lst)) ) )</langsyntaxhighlight>
===Sleeping in child processes===
<langsyntaxhighlight PicoLisplang="picolisp">(de sleepSort (Lst)
(make
(for N Lst
Line 1,328 ⟶ 1,776:
(pop 'Lst)
(task (close @)) ) )
(wait NIL (not Lst)) ) )</langsyntaxhighlight>
Output in both cases:
<pre>: (sleepSort (3 1 4 1 5 9 2 6 5))
Line 1,334 ⟶ 1,782:
===Just printing (no sorted result list)===
Basically the C code.
<langsyntaxhighlight PicoLisplang="picolisp">(for N (3 1 4 1 5 9 2 6 5)
(unless (fork)
(call 'sleep N)
(msg N)
(bye) ) )</langsyntaxhighlight>
Output:
<pre>1
Line 1,352 ⟶ 1,800:
=={{header|Pike}}==
 
<syntaxhighlight lang="pike">
<lang Pike>
#!/usr/bin/env pike
Line 1,374 ⟶ 1,822:
return;
}
</syntaxhighlight>
</lang>
Output :
<pre>
Line 1,388 ⟶ 1,836:
=={{header|Prolog}}==
Works with SWI-Prolog.
<langsyntaxhighlight Prologlang="prolog">sleep_sort(L) :-
thread_pool_create(rosetta, 1024, []) ,
maplist(initsort, L, LID),
Line 1,397 ⟶ 1,845:
thread_create_in_pool(rosetta, (sleep(V), writeln(V)), Id, []).
 
</syntaxhighlight>
</lang>
Output :
<pre> sleep_sort([5, 1, 3, 2, 11, 6, 3, 4]).
Line 1,413 ⟶ 1,861:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">NewMap threads()
 
Procedure Foo(n)
Line 1,429 ⟶ 1,877:
Next
Print("Press ENTER to exit"): Input()
EndIf</langsyntaxhighlight>
<pre>Sleep_sort.exe 3 1 4 1 5 9
1
Line 1,442 ⟶ 1,890:
===Python: Using threading.Timer===
 
<langsyntaxhighlight lang="python">from time import sleep
from threading import Timer
 
Line 1,461 ⟶ 1,909:
print('sleep sort worked for:',x)
else:
print('sleep sort FAILED for:',x)</langsyntaxhighlight>
 
;Sample output:
Line 1,471 ⟶ 1,919:
could be a sole translation from the original version in Bash:
{{Works with|Python 3.5+}}
<langsyntaxhighlight lang="python">#!/usr/bin/env python3
from asyncio import run, sleep, wait
from sys import argv
Line 1,480 ⟶ 1,928:
 
if __name__ == '__main__':
run(wait(list(map(f, map(int, argv[1:])))))</langsyntaxhighlight>
Example usage:
<pre>
Line 1,497 ⟶ 1,945:
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 1,513 ⟶ 1,961:
;; outputs '(2 5 5 7 8 9 10)
(sleep-sort '(5 8 2 7 9 10 5))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>await map -> $delay { start { sleep $delay ; say $delay } },
<6 8 1 12 2 14 5 2 1 0>;</langsyntaxhighlight>
 
{{out}}
Line 1,535 ⟶ 1,983:
This can also be written using reactive programming:
 
<syntaxhighlight lang="raku" perl6line>#!/usr/bin/env perl6raku
use v6;
react whenever Supply.from-list(@*ARGS).start({ .&sleep // +$_ }).flat { .say }</langsyntaxhighlight>
 
{{out}}
Line 1,549 ⟶ 1,997:
 
=={{header|REXX}}==
This sort will accept any manner of numbers, &nbsp; or for that matter, &nbsp; any character string as well.
<br>REXX isn't particular what is being sorted.
<syntaxhighlight lang="rexx">/*REXX program implements a sleep sort (with numbers entered from the command line (CL).*/
 
numeric digits 300 /*over the top, but what the hey! */
This REXX version '''only''' works with Regina REXX &nbsp; (as the program uses the &nbsp; '''fork''' &nbsp;
/* (above) ··· from vaudeville. */
function.
@.= /*placeholder for the array of numbers.*/
<lang rexx>/*REXX program implements a sleep sort (with numbers entered from C.L.).*/
numericstuff= digits1e9 30050 5 40 4 1 100 30 3 12 2 8 9 7 6 6 10 20 0 /*over the top, butalphabetically what··· theso hey!far.*/
parse arg numbers /*obtain optional (above)arguments from ··· fromthe vaudeville.CL*/
#.if numbers='' then numbers= stuff /*Not specified? Then /*placeholder foruse the array of #sdefault.*/
stuffN= 1e9words(numbers) 50 5 40 4 1 100 30 3 12 2 8 9 7 6 6 10 20 0 /*alphabeticallyN is the number of numbers in list. */
parsew= length(N) arg numbers /*letwidth theof user specifyN on the(used CLfor nice output). */
parse upper version !ver . /*obtain which REXX we're running under*/
if numbers='' then numbers=stuff /*Not specified? Then use default*/
N!regina=words (numbers'REXX-REGINA'==left(!ver, 11) ) /*Nindicate (or isnot) theif this number ofis numbersRegina. */
w=length(say N) 'numbers to be sorted:' numbers /*width of N (forinformative niceinformational output).information*/
/*from department of redundancy depart.*/
say N 'numbers to be sorted:' numbers /*informative informational info.*/
do j=1 for N /*let's start to boogie─woogie da sort.*/
 
do @.j=1 word(numbers, j) for N /*let'splug startin toa boogie-woogiesingle number at a time. */
#if datatype(@.j=word(numbers,j 'N') then @.j= @.j / 1 /*plugnormalize init oneif number atit's a time. numeric number*/
if datatype(#.j,'N')!regina then #.j=#.j/1call fork /*normalizeonly REGINA REXX supports it ifFORK a numberBIF.*/
call forksortItem j /*onlystart REGINAa REXXsort supportsfor FORKan array number. */
call sortItem j /*start a sort for array number. */
end /*j*/
 
do forever while \inOrder(N) /*wait for the sorts to complete. */
call sleepdelay 1 /*1one secsecond is minimum effective time.*/
end /*forever while*/ /*well heck, other than zero seconds. */
 
m= max(length(#@.1), length(#@.N) ) /*width of smallest |or largest numnumber. */
say; say 'after sort:' say 'after sort:' /*display a blank line and a title. */
 
do k=1 for N /*list the (sorted) array's elements.*/
say left('', 20) 'array element' right(k, w) '───►' right(#@.k, m)
end /*k*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*───────────────────────────────────SortItem subroutine────────────────*/
sortItem: procedure expose #@.; parse arg ? /*sorts a single (numeric) item. */
do Asort=1 until \switched /*cooksort unsorted array until cooked.it's sorted*/
switched= 0 /*it's all hunky─dorey, happy─dappy /*hunky-dorey so far···*/
do i=1 while #@.i\=='' & \switched
if #@.? >= #@.i then iterate /*thisitem oneis in order. ok*/
parse value #@.? #@.i with #@.i #@.?
switched= 1 /* [↑] swapped one.*/
end /*i*/
if Asort//?==0 then call sleepdelay switched /*sleep if last item*/
end /*Asort*/
return /*Sleeping Beauty awakes. Not to worry: (c) = circa 1697.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*───────────────────────────────────InOrder subroutine─────────────────*/
inOrder: procedure expose #@.; parse arg howMany /*is the array in numerical order? */
do m=1 for howMany-1; next= m+1; if #@.m>#@.next then return 0 /*¬ in order*/
end /*m*/ /*keep looking for fountain of yutyouth. */
return 1 /*yes, indicate with an indicator. */</syntaxhighlight>
Programming note: &nbsp; this REXX program makes use of &nbsp; '''DELAY''' &nbsp; BIF which delays (sleeps) for a specified amount of seconds.
</lang>
<br>Some REXXes don't have a &nbsp; '''DELAY''' &nbsp; BIF, &nbsp; so one is included here &nbsp; ──► &nbsp; [[DELAY.REX]].
'''output''' when using the default input
 
 
{{out|output|text=&nbsp; when using the internal default input:}}
<pre>
19 numbers to be sorted: 1e91E9 50 5 40 4 1 100 30 3 12 2 8 9 7 6 6 10 20 0
 
after sort:
array element 1 ───>───► 0
array element 2 ───>───► 1
array element 3 ───>───► 2
array element 4 ───>───► 3
array element 5 ───>───► 4
array element 6 ───>───► 5
array element 7 ───>───► 6
array element 8 ───>───► 6
array element 9 ───>───► 7
array element 10 ───>───► 8
array element 11 ───>───► 9
array element 12 ───>───► 10
array element 13 ───>───► 12
array element 14 ───>───► 20
array element 15 ───>───► 30
array element 16 ───>───► 40
array element 17 ───>───► 50
array element 18 ───>───► 100
array element 19 ───>───► 1000000000
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'thread'
 
nums = ARGV.collect(&:to_i)
Line 1,642 ⟶ 2,092:
threads.each {|t| t.join}
 
p sorted</langsyntaxhighlight>
 
Example
Line 1,649 ⟶ 2,099:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::thread;
 
fn sleepsort<I: Iterator<Item=u32>>(nums: I) {
Line 1,661 ⟶ 2,111:
fn main() {
sleepsort(std::env::args().skip(1).map(|s| s.parse().unwrap()));
}</langsyntaxhighlight>
Output:
<pre>$ ./sleepsort 50 34 43 3 2
Line 1,672 ⟶ 2,122:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object SleepSort {
 
def main(args: Array[String]): Unit = {
Line 1,688 ⟶ 2,138:
}.start())
 
}</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="bash">$ scala SleepSort 1 3 6 0 9 7 4 2 5 8
0 1 2 3 4 5 5 6 7 8 9 </langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">ARGV.map{.to_i}.map{ |i|
{Sys.sleep(i); say i}.fork;
}.each{.wait};</langsyntaxhighlight>
{{out}}
<pre>% sidef test.sf 5 1 3 2 11 6 4
Line 1,708 ⟶ 2,158:
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">SIMULATION
BEGIN
 
Line 1,727 ⟶ 2,177:
OUTIMAGE;
 
END;</langsyntaxhighlight>
{{out}}
<pre> 1 2 3 3 4 6 7 9
Line 1,734 ⟶ 2,184:
=={{header|SNUSP}}==
Bloated SNUSP is ideally suited to this task, since this the variant adds multithreading and an additional dimension of data space. Sleep time is simulated by the loop delay required to copy each cell value, thereby ensuring that smaller values are printed earlier than larger values. This program requires a Bloated SNUSP interpreter which returns zero on input end-of-file.
<syntaxhighlight lang="snusp">
<lang SNUSP>
/$>\ input until eof
#/?<\?,/ foreach: fork
Line 1,740 ⟶ 2,190:
/:\?-; delay /
\.# print and exit thread
</syntaxhighlight>
</lang>
 
Legend:
Line 1,748 ⟶ 2,198:
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
for i in [5, 2, 4, 6, 1, 7, 20, 14] {
Line 1,759 ⟶ 2,209:
}
 
CFRunLoopRun()</langsyntaxhighlight>
{{out}}
<pre>
Line 1,774 ⟶ 2,224:
=={{header|Tcl}}==
===Tcl 8.5===
<langsyntaxhighlight lang="tcl">#!/bin/env tclsh
set count 0
proc process val {
Line 1,787 ⟶ 2,237:
while {$count < $argc} {
vwait count
}</langsyntaxhighlight>
'''Demo:'''
<pre>
Line 1,806 ⟶ 2,256:
6
</pre>
===Tcl 8.6===
<syntaxhighlight lang="tcl">set sorted {}
lmap x $argv {after $x [list lappend sorted $x]}
while {[llength $sorted] != $argc} {
vwait sorted
}
puts $sorted</syntaxhighlight>
{{out}}
<pre>$ echo 'puts [lmap _ [lrepeat 30 {}] {expr {int(rand() * 100)}}]' | tclsh | tee /dev/tty | xargs tclsh sleepsort.tcl
5 8 70 27 15 80 49 2 69 93 29 1 14 84 43 2 81 44 60 62 8 75 23 61 42 68 79 46 72 65
1 2 2 5 8 8 14 15 23 27 29 42 43 44 46 49 60 61 62 65 68 69 70 72 75 79 80 81 84 93</pre>
 
===Tcl 8.6: coroutine===
<langsyntaxhighlight lang="tcl">#! /usr/bin/env tclsh
package require Tcl 8.6
Line 1,843 ⟶ 2,305:
coroutine c sleep-sort [validate $argv] ::sorted
vwait sorted</langsyntaxhighlight>
'''Demo:'''
<pre>
Line 1,861 ⟶ 2,323:
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="bash">f() {
sleep "$1"
echo "$1"
Line 1,870 ⟶ 2,332:
shift
done
wait</langsyntaxhighlight>
Usage and output:
<pre>
Line 1,880 ⟶ 2,342:
5
9
</pre>
 
=={{header|Visual Basic .NET}}==
<syntaxhighlight lang="vbnet">Imports System.Threading
 
Module Module1
 
Sub SleepSort(items As IEnumerable(Of Integer))
For Each item In items
Task.Factory.StartNew(Sub()
Thread.Sleep(1000 * item)
Console.WriteLine(item)
End Sub)
Next
End Sub
 
Sub Main()
SleepSort({1, 5, 2, 1, 8, 10, 3})
Console.ReadKey()
End Sub
 
End Module</syntaxhighlight>
 
{{out}}
<pre>
1
1
2
3
5
8
10
</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="vlang">
import time
import sync
 
fn main() {
mut wg := sync.new_waitgroup()
test_arr := [3, 2, 1, 4, 1, 7]
wg.add(test_arr.len)
for i, value in test_arr {
go sort(i, value, mut wg)
}
wg.wait()
println('Printed sorted array')
}
 
fn sort(id int, value int, mut wg sync.WaitGroup) {
time.sleep(value * time.millisecond) // can change duration to second or others
println(value)
wg.done()
}
</syntaxhighlight>
 
{{out}}
<pre>
1
1
2
3
4
7
Printed sorted array
</pre>
 
=={{header|Wren}}==
More of a simulation than a 'true' sleep sort.
<syntaxhighlight lang="wren">import "timer" for Timer
import "io" for Stdout
import "os" for Process
 
var args = Process.arguments
var n = args.count
if (n < 2) Fiber.abort("There must be at least two arguments passed.")
var list = args.map{ |a| Num.fromString(a) }.toList
if (list.any { |i| i == null || !i.isInteger || i < 0 } ) {
Fiber.abort("All arguments must be non-negative integers.")
}
var max = list.reduce { |acc, i| acc = (i > acc) ? i : acc }
var fibers = List.filled(max+1, null)
System.print("Before: %(list.join(" "))")
for (i in list) {
var sleepSort = Fiber.new { |i|
Timer.sleep(1000)
Fiber.yield(i)
}
fibers[i] = sleepSort
}
System.write("After : ")
for (i in 0..max) {
var fib = fibers[i]
if (fib) {
System.write("%(fib.call(i)) ")
Stdout.flush()
}
}
System.print()</syntaxhighlight>
 
{{out}}
Sample run:
<pre>
$ wren Sorting_algorithms_Sleep_sort.wren 1 8 3 7 4 6
Before: 1 8 3 7 4 6
After : 1 3 4 6 7 8
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">vm.arglist.apply(fcn(n){ Atomic.sleep(n); print(n) }.launch);
Atomic.waitFor(fcn{ vm.numThreads == 1 }); Atomic.sleep(2); println();</langsyntaxhighlight>
{{out}}
<pre>
1

edit