Sorting algorithms/Sleep sort: Difference between revisions
m
→{{header|Elena}}
(J) |
|||
(11 intermediate revisions by 9 users not shown) | |||
Line 10:
=={{header|Ada}}==
<
with Ada.Command_Line; use Ada.Command_Line;
procedure SleepSort is
Line 24:
TaskList(i) := new PrintTask(Integer'Value(Argument(i)));
end loop;
end SleepSort;</
{{out}}
<pre>./sleepsort 35 21 11 1 2 27 32 7 42 20 50 42 25 41 43 14 46 20 30 8
Line 30:
=={{header|APL}}==
<syntaxhighlight lang="apl">
sleepsort←{{r}⎕TSYNC{r,←⊃⍵,⎕DL ⍵}&¨⍵,r←⍬}
</syntaxhighlight>
=={{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}}==
<
for i, v in SleepSort(items)
result .= v ", "
Line 55 ⟶ 178:
global Sorted
Sorted.Push(v)
}</
{{out}}
<pre>[1, 3, 4, 4, 5, 9]</pre>
=={{header|Bash}}==
<
function sleep_and_echo {
sleep "$1"
Line 71 ⟶ 194:
wait
</syntaxhighlight>
{{out}}
Line 102 ⟶ 225:
{{works with|BBC BASIC for Windows}}
This does not explicitly 'sleep', but uses timers to implement the different delays.
<
DIM test%(9)
Line 125 ⟶ 248:
DEF PROCtask7 : PRINT test%(7) : ENDPROC
DEF PROCtask8 : PRINT test%(8) : ENDPROC
DEF PROCtask9 : PRINT test%(9) : ENDPROC</
'''Output:'''
<pre>
Line 141 ⟶ 264:
=={{header|Brainf***}}==
<syntaxhighlight lang="c">
>>>>>,----------[++++++++
++[->+>+<<]>+>[-<<+>>]+++
Line 150 ⟶ 273:
->>>>>[>>>>>]<-<<<<[<<<<<
]+<]<<<<]>>>>>[>>>>>]<]
</syntaxhighlight>
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 158 ⟶ 281:
=={{header|C}}==
<
#include <unistd.h>
#include <sys/types.h>
Line 170 ⟶ 293:
wait(0);
return 0;
}</
Running it:<syntaxhighlight lang="text">% ./a.out 5 1 3 2 11 6 4
1
2
Line 178 ⟶ 301:
5
6
11</
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#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 207 ⟶ 330:
SleepSort(arguments.Select(int.Parse));
}
}</
===Using Tasks===
<
foreach (var n in input)
Line 219 ⟶ 342:
Console.WriteLine(n);
});
</syntaxhighlight>
Output, i.e. in LINQPad:
Line 230 ⟶ 353:
=={{header|C++}}==
<
#include <chrono>
#include <iostream>
Line 251 ⟶ 374:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 274 ⟶ 397:
=={{header|Clojure}}==
Using core.async
<
(require [clojure.core.async :as async :refer [chan go <! <!! >! timeout]]))
Line 282 ⟶ 405:
(go (<! (timeout (* 1000 i)))
(>! c i)))
(<!! (async/into [] (async/take (count l) c)))))</
<
;=> [1 2 3 4 5 6 7]</
=={{header|CoffeeScript}}==
{{works_with|node.js}}
<
after = (s, f) -> setTimeout f, s*1000
Line 300 ⟶ 423:
input = (parseInt(arg) for arg in process.argv[2...])
sleep_sort input
</syntaxhighlight>
output
<syntaxhighlight lang="text">
> time coffee sleep_sort.coffee 5, 1, 3, 4, 2
1
Line 313 ⟶ 436:
user 0m0.147s
sys 0m0.024s
</syntaxhighlight>
=={{header|Common Lisp}}==
{{works_with|SBCL}}
<
(sleep (/ n 10))
(format t "~a~%" n))
Line 324 ⟶ 447:
(sb-thread:make-thread (lambda() (sleeprint (parse-integer arg)))))
(loop while (not (null (cdr (sb-thread:list-all-threads)))))</
{{Out}}
<pre>$ sbcl --script ss.cl 3 1 4 1 5
Line 335 ⟶ 458:
=={{header|D}}==
<
{
import core.thread, std;
Line 343 ⟶ 466:
write(a, " ");
});
}</
{{out}}
<pre>$ ./sorting_algorithms_sleep_sort 200 20 50 10 80
Line 349 ⟶ 472:
=={{header|Dart}}==
<
void main() async {
Future<void> sleepsort(Iterable<int> input) => Future.wait(input
Line 356 ⟶ 479:
await sleepsort([3, 10, 2, 120, 122, 121, 54]);
}
</syntaxhighlight>
{{out}}
<pre>
Line 369 ⟶ 492:
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 427 ⟶ 550:
Writeln;
ReadLn;
end.</
Output:
<pre>
Line 435 ⟶ 558:
=={{header|Elena}}==
ELENA
<
import system'routines;
import extensions'threading;
Line 447 ⟶ 570:
sleepSort()
{
self.forEach::(n)
{
threadControl.start(
Line 461 ⟶ 584:
}
}
public program()
{
}</
=={{header|Elixir}}==
{{trans|Erlang}}
<
def sleep_sort(args) do
Enum.each(args, fn(arg) -> Process.send_after(self, arg, 5 * arg) end)
Line 486 ⟶ 609:
end
Sort.sleep_sort [2, 4, 8, 12, 35, 2, 12, 1]</
{{out}}
Line 503 ⟶ 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:
<
(run-with-timer (* i 0.001) nil 'message "%d" i))</
The output printed in the *Messages* buffer is:
Line 519 ⟶ 642:
=={{header|Erlang}}==
<
%% -*- erlang -*-
%%! -smp enable -sname sleepsort
Line 536 ⟶ 659:
io:format("~s~n", [Num]),
loop(N - 1)
end.</
{{out}}
<pre>./sleepsort 2 4 8 12 35 2 12 1
Line 549 ⟶ 672:
=={{header|Euphoria}}==
<
integer count
Line 579 ⟶ 702:
task_yield()
end while
end if</
=={{header|F_Sharp|F#}}==
<
let sleepSort (values: seq<int>) =
values
Line 592 ⟶ 715:
|> Async.Ignore
|> Async.RunSynchronously
</syntaxhighlight>
Usage:
<
sleepSort [10; 33; 80; 32]
10
Line 601 ⟶ 724:
33
80
</syntaxhighlight>
=={{header|Factor}}==
<syntaxhighlight lang="factor">
USING: threads calendar concurrency.combinators ;
: sleep-sort ( seq -- ) [ dup seconds sleep . ] parallel-each ;
</syntaxhighlight>
Usage:
<syntaxhighlight lang="factor">
{ 1 9 2 6 3 4 5 8 7 0 } sleep-sort
</syntaxhighlight>
=={{header|Fortran}}==
<syntaxhighlight lang="fortran">
program sleepSort
use omp_lib
Line 652 ⟶ 775:
end subroutine sleepNprint
end program sleepSort
</syntaxhighlight>
Compile and Output:
<pre>
Line 669 ⟶ 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.
<
' compile with: fbc -s console
' compile with: fbc -s console -exx (for bondry check on the array's)
Line 726 ⟶ 849:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>unsorted 5 2 5 6 4 6 9 5 1 2 0
Line 733 ⟶ 856:
=={{header|Go}}==
<
import (
Line 758 ⟶ 881:
fmt.Println(<-out)
}
}</
Usage and output:
<pre>./sleepsort 3 1 4 1 5 9
Line 770 ⟶ 893:
=== Using sync.WaitGroup ===
<
import (
Line 797 ⟶ 920:
}
wg.Wait()
}</
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}}==
<
@Grab(group = 'org.codehaus.gpars', module = 'gpars', version = '1.2.1')
import groovyx.gpars.GParsPool
Line 812 ⟶ 935:
}
}
</syntaxhighlight>
Sample Run:
Line 825 ⟶ 948:
=={{header|Haskell}}==
<
import Control.Concurrent
import Control.Monad
Line 836 ⟶ 959:
main :: IO ()
main = getArgs >>= sleepSort . map read</
===Using mapConcurrently_===
<
import Control.Concurrent
import Control.Concurrent.Async
Line 847 ⟶ 970:
main :: IO ()
main = getArgs >>= sleepSort . map read</
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 855 ⟶ 978:
The following solution only works in Unicon.
<
every insert(t:=set(),mkThread(t,!A))
every spawn(!t) # start threads as closely grouped as possible
Line 863 ⟶ 986:
procedure mkThread(t,n) # 10ms delay scale factor
return create (delay(n*10),delete(t,¤t),n@>&main)
end</
Sample run:
Line 883 ⟶ 1,006:
{{works with|J|903+}}
<
id=:'dumb',":x:6!:9''
wd 'pc ',id
Line 897 ⟶ 1,020:
{{echo R}} scheduledumb poly"0 >:>./ y
EMPTY
}}</
Task example:
<
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</
Note that since t is the result of an RNG, the order of values in t would be different in subsequent attempts. For example:
<
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</
=={{header|Java}}==
{{works with|Java|1.5+}}
<
public class SleepSort {
Line 947 ⟶ 1,070:
sleepSortAndPrint(nums);
}
}</
Output (using "3 1 4 5 2 3 1 6 1 3 2 5 4 6" as arguments):
<pre>1
Line 965 ⟶ 1,088:
=={{header|JavaScript}}==
<
this.forEach(function (n) {
setTimeout(function () { f(n) }, 5 * n)
});
}
</syntaxhighlight>
Usage and output:
<
<pre>
0
Line 986 ⟶ 1,109:
</pre>
<
const res = [];
for (let n of this)
Line 999 ⟶ 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>
=={{header|jq}}==
Line 1,006 ⟶ 1,129:
Doesn't actually sleep. Instead, iterates reducing the values by one until each is zero.
<
def f:
if .unsorted == [] then
Line 1,016 ⟶ 1,139:
end;
{unsorted: [.[] | {v: ., t: .}], sorted: []} | f | .[]
'</
{{out}}
<pre>1
Line 1,029 ⟶ 1,152:
{{works with|Julia|1.6}}
<
U = Vector{T}()
sizehint!(U, length(V))
Line 1,044 ⟶ 1,167:
v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", sleepsort(v))</
{{out}}
Line 1,051 ⟶ 1,174:
=={{header|Kotlin}}==
<
import kotlin.concurrent.thread
Line 1,073 ⟶ 1,196:
println("Unsorted: ${list.joinToString(" ")}")
sleepSort(list, 50)
}</
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 1,085 ⟶ 1,238:
Here's a slow implementation using only stock C Lua:
<
local t0 = os.time()
while os.time() - t0 <= n do
Line 1,111 ⟶ 1,264:
end
end
end</
By installing LuaSocket, you can get better than 1-second precision on the clock, and therefore faster output:
<
function sleeprint(n)
Line 1,143 ⟶ 1,296:
end
end
end</
Either way, the output is the same:
Line 1,164 ⟶ 1,317:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
SleepSort@{1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0};</
{{Out}}
<pre>
Line 1,183 ⟶ 1,336:
As implemented this sample goes beyond the scope of the task as defined; it will handle negative numbers.
<
options replace format comments java crossref symbols nobinary
import java.util.concurrent.CountDownLatch
Line 1,242 ⟶ 1,395:
parent.getDoneLatch().countDown() -- this one's done; decrement the latch
return
</syntaxhighlight>
'''Output:'''
<pre>
Line 1,251 ⟶ 1,404:
=={{header|Nim}}==
Compile with <code>nim --threads:on c sleepsort</code>:
<
proc single(n: int) =
Line 1,263 ⟶ 1,416:
thr.joinThreads
main()</
Usage:
<pre>$ ./sleepsort 5 1 3 2 11 6 4
Line 1,275 ⟶ 1,428:
=={{header|Objeck}}==
<
use System.Concurrency;
use Collection;
Line 1,307 ⟶ 1,460:
}
}
</syntaxhighlight>
=={{header|Objective-C}}==
<
int main(int argc, char **argv)
Line 1,323 ⟶ 1,476:
}
[queue waitUntilAllOperationsAreFinished];
}</
Rather than having multiple operations that sleep, we could also dispatch the tasks after a delay:
<
int main(int argc, char **argv)
Line 1,335 ⟶ 1,488:
^{ NSLog(@"%d\n", i); });
}
}</
=={{header|Oforth}}==
Line 1,343 ⟶ 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.
<
: sleepSort(l)
Line 1,349 ⟶ 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) ;</
{{out}}
Line 1,366 ⟶ 1,519:
=={{header|Ol}}==
<
(define (sleep-sort lst)
(for-each (lambda (timeout)
Line 1,375 ⟶ 1,528:
(sleep-sort '(5 8 2 7 9 10 5))
</syntaxhighlight>
{{Out}}
<pre>
Line 1,390 ⟶ 1,543:
{{works with|Free Pascal}}
my limit under linux was 4000 threads nearly 2 GB.
<
program sleepsort;
{$IFDEF FPC}
Line 1,490 ⟶ 1,643:
readln;
{$ENDIF}
end.</
{{out}}
<pre>time ./sleepsort
Line 1,501 ⟶ 1,654:
=={{header|Perl}}==
Basically the C code.
<
sleep $_;
print "$_\n";
wait;</
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:
<
$ret = Coro::Channel->new;
@nums = qw(1 32 2 59 2 39 43 15 8 9 12 9 11);
Line 1,519 ⟶ 1,672:
}
print $ret->get,"\n" for 1..@nums;</
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
<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>
<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>
<span style="color: #0000FF;">?</span> <span style="color: #000000;">key</span> <span style="color: #000080;font-style:italic;">-- (or maybe res &= key)</span>
<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>
<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>
<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>
<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>
<span style="color: #008080;">else</span>
<span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<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>
<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>
<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>
<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>
<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>
<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;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<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>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
=={{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===
<
(make
(for (I . N) Lst
Line 1,562 ⟶ 1,767:
(pop 'Lst)
(task (- I)) ) )
(wait NIL (not Lst)) ) )</
===Sleeping in child processes===
<
(make
(for N Lst
Line 1,571 ⟶ 1,776:
(pop 'Lst)
(task (close @)) ) )
(wait NIL (not Lst)) ) )</
Output in both cases:
<pre>: (sleepSort (3 1 4 1 5 9 2 6 5))
Line 1,577 ⟶ 1,782:
===Just printing (no sorted result list)===
Basically the C code.
<
(unless (fork)
(call 'sleep N)
(msg N)
(bye) ) )</
Output:
<pre>1
Line 1,595 ⟶ 1,800:
=={{header|Pike}}==
<syntaxhighlight lang="pike">
#!/usr/bin/env pike
Line 1,617 ⟶ 1,822:
return;
}
</syntaxhighlight>
Output :
<pre>
Line 1,631 ⟶ 1,836:
=={{header|Prolog}}==
Works with SWI-Prolog.
<
thread_pool_create(rosetta, 1024, []) ,
maplist(initsort, L, LID),
Line 1,640 ⟶ 1,845:
thread_create_in_pool(rosetta, (sleep(V), writeln(V)), Id, []).
</syntaxhighlight>
Output :
<pre> sleep_sort([5, 1, 3, 2, 11, 6, 3, 4]).
Line 1,656 ⟶ 1,861:
=={{header|PureBasic}}==
<
Procedure Foo(n)
Line 1,672 ⟶ 1,877:
Next
Print("Press ENTER to exit"): Input()
EndIf</
<pre>Sleep_sort.exe 3 1 4 1 5 9
1
Line 1,685 ⟶ 1,890:
===Python: Using threading.Timer===
<
from threading import Timer
Line 1,704 ⟶ 1,909:
print('sleep sort worked for:',x)
else:
print('sleep sort FAILED for:',x)</
;Sample output:
Line 1,714 ⟶ 1,919:
could be a sole translation from the original version in Bash:
{{Works with|Python 3.5+}}
<
from asyncio import run, sleep, wait
from sys import argv
Line 1,723 ⟶ 1,928:
if __name__ == '__main__':
run(wait(map(f, map(int, argv[1:]))))</
Example usage:
<pre>
Line 1,740 ⟶ 1,945:
=={{header|Racket}}==
<
#lang racket
Line 1,756 ⟶ 1,961:
;; outputs '(2 5 5 7 8 9 10)
(sleep-sort '(5 8 2 7 9 10 5))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
<6 8 1 12 2 14 5 2 1 0>;</
{{out}}
Line 1,778 ⟶ 1,983:
This can also be written using reactive programming:
<syntaxhighlight lang="raku"
use v6;
react whenever Supply.from-list(@*ARGS).start({ .&sleep // +$_ }).flat { .say }</
{{out}}
Line 1,794 ⟶ 1,999:
This sort will accept any manner of numbers, or for that matter, any character string as well.
<br>REXX isn't particular what is being sorted.
<
numeric digits 300 /*over the top, but what the hey! */
/* (above) ··· from vaudeville. */
Line 1,841 ⟶ 2,046:
do m=1 for howMany-1; next= m+1; if @.m>@.next then return 0 /*¬ in order*/
end /*m*/ /*keep looking for fountain of youth. */
return 1 /*yes, indicate with an indicator. */</
Programming note: this REXX program makes use of '''DELAY''' BIF which delays (sleeps) for a specified amount of seconds.
<br>Some REXXes don't have a '''DELAY''' BIF, so one is included here ──► [[DELAY.REX]].
Line 1,873 ⟶ 2,078:
=={{header|Ruby}}==
<
nums = ARGV.collect(&:to_i)
Line 1,887 ⟶ 2,092:
threads.each {|t| t.join}
p sorted</
Example
Line 1,894 ⟶ 2,099:
=={{header|Rust}}==
<
fn sleepsort<I: Iterator<Item=u32>>(nums: I) {
Line 1,906 ⟶ 2,111:
fn main() {
sleepsort(std::env::args().skip(1).map(|s| s.parse().unwrap()));
}</
Output:
<pre>$ ./sleepsort 50 34 43 3 2
Line 1,917 ⟶ 2,122:
=={{header|Scala}}==
<
def main(args: Array[String]): Unit = {
Line 1,933 ⟶ 2,138:
}.start())
}</
{{out}}
<
0 1 2 3 4 5 5 6 7 8 9 </
=={{header|Sidef}}==
<
{Sys.sleep(i); say i}.fork;
}.each{.wait};</
{{out}}
<pre>% sidef test.sf 5 1 3 2 11 6 4
Line 1,953 ⟶ 2,158:
=={{header|Simula}}==
<
BEGIN
Line 1,972 ⟶ 2,177:
OUTIMAGE;
END;</
{{out}}
<pre> 1 2 3 3 4 6 7 9
Line 1,979 ⟶ 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">
/$>\ input until eof
#/?<\?,/ foreach: fork
Line 1,985 ⟶ 2,190:
/:\?-; delay /
\.# print and exit thread
</syntaxhighlight>
Legend:
Line 1,993 ⟶ 2,198:
=={{header|Swift}}==
<
for i in [5, 2, 4, 6, 1, 7, 20, 14] {
Line 2,004 ⟶ 2,209:
}
CFRunLoopRun()</
{{out}}
<pre>
Line 2,019 ⟶ 2,224:
=={{header|Tcl}}==
===Tcl 8.5===
<
set count 0
proc process val {
Line 2,032 ⟶ 2,237:
while {$count < $argc} {
vwait count
}</
'''Demo:'''
<pre>
Line 2,052 ⟶ 2,257:
</pre>
===Tcl 8.6===
<
lmap x $argv {after $x [list lappend sorted $x]}
while {[llength $sorted] != $argc} {
vwait sorted
}
puts $sorted</
{{out}}
<pre>$ echo 'puts [lmap _ [lrepeat 30 {}] {expr {int(rand() * 100)}}]' | tclsh | tee /dev/tty | xargs tclsh sleepsort.tcl
Line 2,064 ⟶ 2,269:
===Tcl 8.6: coroutine===
<
package require Tcl 8.6
Line 2,100 ⟶ 2,305:
coroutine c sleep-sort [validate $argv] ::sorted
vwait sorted</
'''Demo:'''
<pre>
Line 2,118 ⟶ 2,323:
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
<
sleep "$1"
echo "$1"
Line 2,127 ⟶ 2,332:
shift
done
wait</
Usage and output:
<pre>
Line 2,137 ⟶ 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.
<
import "io" for Stdout
import "os" for Process
Line 2,170 ⟶ 2,441:
}
}
System.print()</
{{out}}
Sample run:
<pre>
$ wren
Before: 1 8 3 7 4 6
After : 1 3 4 6 7 8
Line 2,181 ⟶ 2,452:
=={{header|zkl}}==
<
Atomic.waitFor(fcn{ vm.numThreads == 1 }); Atomic.sleep(2); println();</
{{out}}
<pre>
|