Sorting algorithms/Sleep sort: Difference between revisions

Content added Content deleted
(Implementation for Visual Basic .NET added)
m (syntax highlighting fixup automation)
Line 10: Line 10:


=={{header|Ada}}==
=={{header|Ada}}==
<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Command_Line; use Ada.Command_Line;
procedure SleepSort is
procedure SleepSort is
Line 24: Line 24:
TaskList(i) := new PrintTask(Integer'Value(Argument(i)));
TaskList(i) := new PrintTask(Integer'Value(Argument(i)));
end loop;
end loop;
end SleepSort;</lang>
end SleepSort;</syntaxhighlight>
{{out}}
{{out}}
<pre>./sleepsort 35 21 11 1 2 27 32 7 42 20 50 42 25 41 43 14 46 20 30 8
<pre>./sleepsort 35 21 11 1 2 27 32 7 42 20 50 42 25 41 43 14 46 20 30 8
Line 30: Line 30:


=={{header|APL}}==
=={{header|APL}}==
<syntaxhighlight lang="apl">
<lang APL>
sleepsort←{{r}⎕TSYNC{r,←⊃⍵,⎕DL ⍵}&¨⍵,r←⍬}
sleepsort←{{r}⎕TSYNC{r,←⊃⍵,⎕DL ⍵}&¨⍵,r←⍬}
</syntaxhighlight>
</lang>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>items := [1,5,4,9,3,4]
<syntaxhighlight lang="autohotkey">items := [1,5,4,9,3,4]
for i, v in SleepSort(items)
for i, v in SleepSort(items)
result .= v ", "
result .= v ", "
Line 55: Line 55:
global Sorted
global Sorted
Sorted.Push(v)
Sorted.Push(v)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[1, 3, 4, 4, 5, 9]</pre>
<pre>[1, 3, 4, 4, 5, 9]</pre>


=={{header|Bash}}==
=={{header|Bash}}==
<lang bash>
<syntaxhighlight lang="bash">
function sleep_and_echo {
function sleep_and_echo {
sleep "$1"
sleep "$1"
Line 71: Line 71:


wait
wait
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 102: Line 102:
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
This does not explicitly 'sleep', but uses timers to implement the different delays.
This does not explicitly 'sleep', but uses timers to implement the different delays.
<lang bbcbasic> INSTALL @lib$+"TIMERLIB"
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"TIMERLIB"
DIM test%(9)
DIM test%(9)
Line 125: Line 125:
DEF PROCtask7 : PRINT test%(7) : ENDPROC
DEF PROCtask7 : PRINT test%(7) : ENDPROC
DEF PROCtask8 : PRINT test%(8) : ENDPROC
DEF PROCtask8 : PRINT test%(8) : ENDPROC
DEF PROCtask9 : PRINT test%(9) : ENDPROC</lang>
DEF PROCtask9 : PRINT test%(9) : ENDPROC</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 141: Line 141:


=={{header|Brainf***}}==
=={{header|Brainf***}}==
<syntaxhighlight lang="c">
<lang C>
>>>>>,----------[++++++++
>>>>>,----------[++++++++
++[->+>+<<]>+>[-<<+>>]+++
++[->+>+<<]>+>[-<<+>>]+++
Line 150: Line 150:
->>>>>[>>>>>]<-<<<<[<<<<<
->>>>>[>>>>>]<-<<<<[<<<<<
]+<]<<<<]>>>>>[>>>>>]<]
]+<]<<<<]>>>>>[>>>>>]<]
</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.
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: Line 158:


=={{header|C}}==
=={{header|C}}==
<lang C>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>
#include <unistd.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/types.h>
Line 170: Line 170:
wait(0);
wait(0);
return 0;
return 0;
}</lang>
}</syntaxhighlight>
Running it:<lang>% ./a.out 5 1 3 2 11 6 4
Running it:<syntaxhighlight lang="text">% ./a.out 5 1 3 2 11 6 4
1
1
2
2
Line 178: Line 178:
5
5
6
6
11</lang>
11</syntaxhighlight>
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.
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#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 207: Line 207:
SleepSort(arguments.Select(int.Parse));
SleepSort(arguments.Select(int.Parse));
}
}
}</lang>
}</syntaxhighlight>


===Using Tasks===
===Using Tasks===


<lang csharp>var input = new[] { 1, 9, 2, 1, 3 };
<syntaxhighlight lang="csharp">var input = new[] { 1, 9, 2, 1, 3 };


foreach (var n in input)
foreach (var n in input)
Line 219: Line 219:
Console.WriteLine(n);
Console.WriteLine(n);
});
});
</syntaxhighlight>
</lang>


Output, i.e. in LINQPad:
Output, i.e. in LINQPad:
Line 230: Line 230:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>
<syntaxhighlight lang="cpp">
#include <chrono>
#include <chrono>
#include <iostream>
#include <iostream>
Line 251: Line 251:
}
}
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 274: Line 274:
=={{header|Clojure}}==
=={{header|Clojure}}==
Using core.async
Using core.async
<lang clojure>(ns sleepsort.core
<syntaxhighlight lang="clojure">(ns sleepsort.core
(require [clojure.core.async :as async :refer [chan go <! <!! >! timeout]]))
(require [clojure.core.async :as async :refer [chan go <! <!! >! timeout]]))


Line 282: Line 282:
(go (<! (timeout (* 1000 i)))
(go (<! (timeout (* 1000 i)))
(>! c i)))
(>! c i)))
(<!! (async/into [] (async/take (count l) c)))))</lang>
(<!! (async/into [] (async/take (count l) c)))))</syntaxhighlight>
<lang clojure>(sleep-sort [4 5 3 1 2 7 6])
<syntaxhighlight lang="clojure">(sleep-sort [4 5 3 1 2 7 6])
;=> [1 2 3 4 5 6 7]</lang>
;=> [1 2 3 4 5 6 7]</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
{{works_with|node.js}}
{{works_with|node.js}}
<lang coffeescript>
<syntaxhighlight lang="coffeescript">
after = (s, f) -> setTimeout f, s*1000
after = (s, f) -> setTimeout f, s*1000


Line 300: Line 300:
input = (parseInt(arg) for arg in process.argv[2...])
input = (parseInt(arg) for arg in process.argv[2...])
sleep_sort input
sleep_sort input
</syntaxhighlight>
</lang>
output
output
<lang>
<syntaxhighlight lang="text">
> time coffee sleep_sort.coffee 5, 1, 3, 4, 2
> time coffee sleep_sort.coffee 5, 1, 3, 4, 2
1
1
Line 313: Line 313:
user 0m0.147s
user 0m0.147s
sys 0m0.024s
sys 0m0.024s
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
{{works_with|SBCL}}
{{works_with|SBCL}}
<lang lisp>(defun sleeprint(n)
<syntaxhighlight lang="lisp">(defun sleeprint(n)
(sleep (/ n 10))
(sleep (/ n 10))
(format t "~a~%" n))
(format t "~a~%" n))
Line 324: Line 324:
(sb-thread:make-thread (lambda() (sleeprint (parse-integer arg)))))
(sb-thread:make-thread (lambda() (sleeprint (parse-integer arg)))))


(loop while (not (null (cdr (sb-thread:list-all-threads)))))</lang>
(loop while (not (null (cdr (sb-thread:list-all-threads)))))</syntaxhighlight>
{{Out}}
{{Out}}
<pre>$ sbcl --script ss.cl 3 1 4 1 5
<pre>$ sbcl --script ss.cl 3 1 4 1 5
Line 335: Line 335:


=={{header|D}}==
=={{header|D}}==
<lang d>void main(string[] args)
<syntaxhighlight lang="d">void main(string[] args)
{
{
import core.thread, std;
import core.thread, std;
Line 343: Line 343:
write(a, " ");
write(a, " ");
});
});
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>$ ./sorting_algorithms_sleep_sort 200 20 50 10 80
<pre>$ ./sorting_algorithms_sleep_sort 200 20 50 10 80
Line 349: Line 349:


=={{header|Dart}}==
=={{header|Dart}}==
<lang dart>
<syntaxhighlight lang="dart">
void main() async {
void main() async {
Future<void> sleepsort(Iterable<int> input) => Future.wait(input
Future<void> sleepsort(Iterable<int> input) => Future.wait(input
Line 356: Line 356:
await sleepsort([3, 10, 2, 120, 122, 121, 54]);
await sleepsort([3, 10, 2, 120, 122, 121, 54]);
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 369: Line 369:


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program SleepSortDemo;
<syntaxhighlight lang="delphi">program SleepSortDemo;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 427: Line 427:
Writeln;
Writeln;
ReadLn;
ReadLn;
end.</lang>
end.</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 436: Line 436:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 5.0 :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
import system'routines;
import system'routines;
import extensions'threading;
import extensions'threading;
Line 467: Line 467:
console.readChar()
console.readChar()
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Erlang}}
{{trans|Erlang}}
<lang elixir>defmodule Sort do
<syntaxhighlight lang="elixir">defmodule Sort do
def sleep_sort(args) do
def sleep_sort(args) do
Enum.each(args, fn(arg) -> Process.send_after(self, arg, 5 * arg) end)
Enum.each(args, fn(arg) -> Process.send_after(self, arg, 5 * arg) end)
Line 486: Line 486:
end
end


Sort.sleep_sort [2, 4, 8, 12, 35, 2, 12, 1]</lang>
Sort.sleep_sort [2, 4, 8, 12, 35, 2, 12, 1]</syntaxhighlight>


{{out}}
{{out}}
Line 503: Line 503:
GNU Emacs supports threads, but it's more straightforward to do this by just using timers.
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:
Evaluate in the *scratch* buffer by typing <code>C-M-x</code> on the expression:
<lang Lisp>(dolist (i '(3 1 4 1 5 92 65 3 5 89 79 3))
<syntaxhighlight lang="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))</lang>
(run-with-timer (* i 0.001) nil 'message "%d" i))</syntaxhighlight>


The output printed in the *Messages* buffer is:
The output printed in the *Messages* buffer is:
Line 519: Line 519:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>#!/usr/bin/env escript
<syntaxhighlight lang="erlang">#!/usr/bin/env escript
%% -*- erlang -*-
%% -*- erlang -*-
%%! -smp enable -sname sleepsort
%%! -smp enable -sname sleepsort
Line 536: Line 536:
io:format("~s~n", [Num]),
io:format("~s~n", [Num]),
loop(N - 1)
loop(N - 1)
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>./sleepsort 2 4 8 12 35 2 12 1
<pre>./sleepsort 2 4 8 12 35 2 12 1
Line 549: Line 549:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>include get.e
<syntaxhighlight lang="euphoria">include get.e


integer count
integer count
Line 579: Line 579:
task_yield()
task_yield()
end while
end while
end if</lang>
end if</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
let sleepSort (values: seq<int>) =
let sleepSort (values: seq<int>) =
values
values
Line 592: Line 592:
|> Async.Ignore
|> Async.Ignore
|> Async.RunSynchronously
|> Async.RunSynchronously
</syntaxhighlight>
</lang>


Usage:
Usage:
<lang fsharp>
<syntaxhighlight lang="fsharp">
sleepSort [10; 33; 80; 32]
sleepSort [10; 33; 80; 32]
10
10
Line 601: Line 601:
33
33
80
80
</syntaxhighlight>
</lang>


=={{header|Factor}}==
=={{header|Factor}}==


<syntaxhighlight lang="factor">
<lang Factor>
USING: threads calendar concurrency.combinators ;
USING: threads calendar concurrency.combinators ;


: sleep-sort ( seq -- ) [ dup seconds sleep . ] parallel-each ;
: sleep-sort ( seq -- ) [ dup seconds sleep . ] parallel-each ;
</syntaxhighlight>
</lang>


Usage:
Usage:


<syntaxhighlight lang="factor">
<lang Factor>
{ 1 9 2 6 3 4 5 8 7 0 } sleep-sort
{ 1 9 2 6 3 4 5 8 7 0 } sleep-sort
</syntaxhighlight>
</lang>


=={{header|Fortran}}==
=={{header|Fortran}}==
<syntaxhighlight lang="fortran">
<lang Fortran>
program sleepSort
program sleepSort
use omp_lib
use omp_lib
Line 652: Line 652:
end subroutine sleepNprint
end subroutine sleepNprint
end program sleepSort
end program sleepSort
</syntaxhighlight>
</lang>
Compile and Output:
Compile and Output:
<pre>
<pre>
Line 669: Line 669:
Can't use FreeBASIC '''sleep''' since it halts the program.
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.
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.
<lang freebasic>' version 21-10-2016
<syntaxhighlight lang="freebasic">' version 21-10-2016
' compile with: fbc -s console
' compile with: fbc -s console
' compile with: fbc -s console -exx (for bondry check on the array's)
' compile with: fbc -s console -exx (for bondry check on the array's)
Line 726: Line 726:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>unsorted 5 2 5 6 4 6 9 5 1 2 0
<pre>unsorted 5 2 5 6 4 6 9 5 1 2 0
Line 733: Line 733:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 758: Line 758:
fmt.Println(<-out)
fmt.Println(<-out)
}
}
}</lang>
}</syntaxhighlight>
Usage and output:
Usage and output:
<pre>./sleepsort 3 1 4 1 5 9
<pre>./sleepsort 3 1 4 1 5 9
Line 770: Line 770:


=== Using sync.WaitGroup ===
=== Using sync.WaitGroup ===
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 797: Line 797:
}
}
wg.Wait()
wg.Wait()
}</lang>
}</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.
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}}==
=={{header|Groovy}}==
<lang groovy>
<syntaxhighlight lang="groovy">
@Grab(group = 'org.codehaus.gpars', module = 'gpars', version = '1.2.1')
@Grab(group = 'org.codehaus.gpars', module = 'gpars', version = '1.2.1')
import groovyx.gpars.GParsPool
import groovyx.gpars.GParsPool
Line 812: Line 812:
}
}
}
}
</syntaxhighlight>
</lang>


Sample Run:
Sample Run:
Line 825: Line 825:
=={{header|Haskell}}==
=={{header|Haskell}}==


<lang haskell>import System.Environment
<syntaxhighlight lang="haskell">import System.Environment
import Control.Concurrent
import Control.Concurrent
import Control.Monad
import Control.Monad
Line 836: Line 836:


main :: IO ()
main :: IO ()
main = getArgs >>= sleepSort . map read</lang>
main = getArgs >>= sleepSort . map read</syntaxhighlight>


===Using mapConcurrently_===
===Using mapConcurrently_===
<lang haskell>import System.Environment
<syntaxhighlight lang="haskell">import System.Environment
import Control.Concurrent
import Control.Concurrent
import Control.Concurrent.Async
import Control.Concurrent.Async
Line 847: Line 847:


main :: IO ()
main :: IO ()
main = getArgs >>= sleepSort . map read</lang>
main = getArgs >>= sleepSort . map read</syntaxhighlight>


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.
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: Line 855:
The following solution only works in Unicon.
The following solution only works in Unicon.


<lang unicon>procedure main(A)
<syntaxhighlight lang="unicon">procedure main(A)
every insert(t:=set(),mkThread(t,!A))
every insert(t:=set(),mkThread(t,!A))
every spawn(!t) # start threads as closely grouped as possible
every spawn(!t) # start threads as closely grouped as possible
Line 863: Line 863:
procedure mkThread(t,n) # 10ms delay scale factor
procedure mkThread(t,n) # 10ms delay scale factor
return create (delay(n*10),delete(t,&current),n@>&main)
return create (delay(n*10),delete(t,&current),n@>&main)
end</lang>
end</syntaxhighlight>


Sample run:
Sample run:
Line 883: Line 883:


{{works with|J|903+}}
{{works with|J|903+}}
<lang J>scheduledumb=: {{
<syntaxhighlight lang="j">scheduledumb=: {{
id=:'dumb',":x:6!:9''
id=:'dumb',":x:6!:9''
wd 'pc ',id
wd 'pc ',id
Line 897: Line 897:
{{echo R}} scheduledumb poly"0 >:>./ y
{{echo R}} scheduledumb poly"0 >:>./ y
EMPTY
EMPTY
}}</lang>
}}</syntaxhighlight>


Task example:
Task example:


<lang J> t=: ?~30
<syntaxhighlight lang="j"> t=: ?~30
t
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
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
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</lang>
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:
Note that since t is the result of an RNG, the order of values in t would be different in subsequent attempts. For example:


<lang J> t=: ?~30
<syntaxhighlight lang="j"> t=: ?~30
t
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
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
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</lang>
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}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java5>import java.util.concurrent.CountDownLatch;
<syntaxhighlight lang="java5">import java.util.concurrent.CountDownLatch;


public class SleepSort {
public class SleepSort {
Line 947: Line 947:
sleepSortAndPrint(nums);
sleepSortAndPrint(nums);
}
}
}</lang>
}</syntaxhighlight>
Output (using "3 1 4 5 2 3 1 6 1 3 2 5 4 6" as arguments):
Output (using "3 1 4 5 2 3 1 6 1 3 2 5 4 6" as arguments):
<pre>1
<pre>1
Line 965: Line 965:


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<lang javascript>Array.prototype.timeoutSort = function (f) {
<syntaxhighlight lang="javascript">Array.prototype.timeoutSort = function (f) {
this.forEach(function (n) {
this.forEach(function (n) {
setTimeout(function () { f(n) }, 5 * n)
setTimeout(function () { f(n) }, 5 * n)
});
});
}
}
</syntaxhighlight>
</lang>
Usage and output:
Usage and output:
<lang javascript>[1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0].timeoutSort(function(n) { document.write(n + '<br>'); })</lang>
<syntaxhighlight lang="javascript">[1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0].timeoutSort(function(n) { document.write(n + '<br>'); })</syntaxhighlight>
<pre>
<pre>
0
0
Line 986: Line 986:
</pre>
</pre>


<lang javascript>Array.prototype.sleepSort = function(callback) {
<syntaxhighlight lang="javascript">Array.prototype.sleepSort = function(callback) {
const res = [];
const res = [];
for (let n of this)
for (let n of this)
Line 999: Line 999:
[1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0].sleepSort(console.log);
[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 ]
// [ 1, 0, 2, 3, 4, 5, 5, 6, 7, 8, 9 ]
</syntaxhighlight>
</lang>


=={{header|jq}}==
=={{header|jq}}==
Line 1,006: Line 1,006:
Doesn't actually sleep. Instead, iterates reducing the values by one until each is zero.
Doesn't actually sleep. Instead, iterates reducing the values by one until each is zero.


<lang jq>echo '[5, 1, 3, 2, 11, 6, 4]' | jq '
<syntaxhighlight lang="jq">echo '[5, 1, 3, 2, 11, 6, 4]' | jq '
def f:
def f:
if .unsorted == [] then
if .unsorted == [] then
Line 1,016: Line 1,016:
end;
end;
{unsorted: [.[] | {v: ., t: .}], sorted: []} | f | .[]
{unsorted: [.[] | {v: ., t: .}], sorted: []} | f | .[]
'</lang>
'</syntaxhighlight>
{{out}}
{{out}}
<pre>1
<pre>1
Line 1,029: Line 1,029:
{{works with|Julia|1.6}}
{{works with|Julia|1.6}}


<lang julia>function sleepsort(V::Vector{T}) where {T <: Real}
<syntaxhighlight lang="julia">function sleepsort(V::Vector{T}) where {T <: Real}
U = Vector{T}()
U = Vector{T}()
sizehint!(U, length(V))
sizehint!(U, length(V))
Line 1,044: Line 1,044:


v = rand(-10:10, 10)
v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", sleepsort(v))</lang>
println("# unordered: $v\n -> ordered: ", sleepsort(v))</syntaxhighlight>


{{out}}
{{out}}
Line 1,051: Line 1,051:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.51
<syntaxhighlight lang="scala">// version 1.1.51


import kotlin.concurrent.thread
import kotlin.concurrent.thread
Line 1,073: Line 1,073:
println("Unsorted: ${list.joinToString(" ")}")
println("Unsorted: ${list.joinToString(" ")}")
sleepSort(list, 50)
sleepSort(list, 50)
}</lang>
}</syntaxhighlight>


Sample output:
Sample output:
Line 1,085: Line 1,085:
Here's a slow implementation using only stock C Lua:
Here's a slow implementation using only stock C Lua:


<lang lua>function sleeprint(n)
<syntaxhighlight lang="lua">function sleeprint(n)
local t0 = os.time()
local t0 = os.time()
while os.time() - t0 <= n do
while os.time() - t0 <= n do
Line 1,111: Line 1,111:
end
end
end
end
end</lang>
end</syntaxhighlight>


By installing LuaSocket, you can get better than 1-second precision on the clock, and therefore faster output:
By installing LuaSocket, you can get better than 1-second precision on the clock, and therefore faster output:


<lang lua>socket = require 'socket'
<syntaxhighlight lang="lua">socket = require 'socket'


function sleeprint(n)
function sleeprint(n)
Line 1,143: Line 1,143:
end
end
end
end
end</lang>
end</syntaxhighlight>


Either way, the output is the same:
Either way, the output is the same:
Line 1,164: Line 1,164:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang mathematica>SleepSort = RunScheduledTask[Print@#, {#, 1}] & /@ # &;
<syntaxhighlight lang="mathematica">SleepSort = RunScheduledTask[Print@#, {#, 1}] & /@ # &;
SleepSort@{1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0};</lang>
SleepSort@{1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0};</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,183: Line 1,183:
As implemented this sample goes beyond the scope of the task as defined; it will handle negative numbers.
As implemented this sample goes beyond the scope of the task as defined; it will handle negative numbers.


<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary
import java.util.concurrent.CountDownLatch
import java.util.concurrent.CountDownLatch
Line 1,242: Line 1,242:
parent.getDoneLatch().countDown() -- this one's done; decrement the latch
parent.getDoneLatch().countDown() -- this one's done; decrement the latch
return
return
</syntaxhighlight>
</lang>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 1,251: Line 1,251:
=={{header|Nim}}==
=={{header|Nim}}==
Compile with <code>nim --threads:on c sleepsort</code>:
Compile with <code>nim --threads:on c sleepsort</code>:
<lang nim>import os, strutils
<syntaxhighlight lang="nim">import os, strutils


proc single(n: int) =
proc single(n: int) =
Line 1,263: Line 1,263:
thr.joinThreads
thr.joinThreads


main()</lang>
main()</syntaxhighlight>
Usage:
Usage:
<pre>$ ./sleepsort 5 1 3 2 11 6 4
<pre>$ ./sleepsort 5 1 3 2 11 6 4
Line 1,275: Line 1,275:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
use System.Concurrency;
use System.Concurrency;
use Collection;
use Collection;
Line 1,307: Line 1,307:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


int main(int argc, char **argv)
int main(int argc, char **argv)
Line 1,323: Line 1,323:
}
}
[queue waitUntilAllOperationsAreFinished];
[queue waitUntilAllOperationsAreFinished];
}</lang>
}</syntaxhighlight>
Rather than having multiple operations that sleep, we could also dispatch the tasks after a delay:
Rather than having multiple operations that sleep, we could also dispatch the tasks after a delay:
<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


int main(int argc, char **argv)
int main(int argc, char **argv)
Line 1,335: Line 1,335:
^{ NSLog(@"%d\n", i); });
^{ NSLog(@"%d\n", i); });
}
}
}</lang>
}</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 1,343: Line 1,343:
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.
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.


<lang Oforth>import: parallel
<syntaxhighlight lang="oforth">import: parallel


: sleepSort(l)
: sleepSort(l)
Line 1,349: Line 1,349:
Channel new ->ch
Channel new ->ch
l forEach: n [ #[ n dup 20 * sleep ch send drop ] & ]
l forEach: n [ #[ n dup 20 * sleep ch send drop ] & ]
ListBuffer newSize(l size) #[ ch receive over add ] times(l size) ;</lang>
ListBuffer newSize(l size) #[ ch receive over add ] times(l size) ;</syntaxhighlight>


{{out}}
{{out}}
Line 1,366: Line 1,366:


=={{header|Ol}}==
=={{header|Ol}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(define (sleep-sort lst)
(define (sleep-sort lst)
(for-each (lambda (timeout)
(for-each (lambda (timeout)
Line 1,375: Line 1,375:


(sleep-sort '(5 8 2 7 9 10 5))
(sleep-sort '(5 8 2 7 9 10 5))
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,390: Line 1,390:
{{works with|Free Pascal}}
{{works with|Free Pascal}}
my limit under linux was 4000 threads nearly 2 GB.
my limit under linux was 4000 threads nearly 2 GB.
<lang pascal>
<syntaxhighlight lang="pascal">
program sleepsort;
program sleepsort;
{$IFDEF FPC}
{$IFDEF FPC}
Line 1,490: Line 1,490:
readln;
readln;
{$ENDIF}
{$ENDIF}
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>time ./sleepsort
<pre>time ./sleepsort
Line 1,501: Line 1,501:
=={{header|Perl}}==
=={{header|Perl}}==
Basically the C code.
Basically the C code.
<lang Perl>1 while ($_ = shift and @ARGV and !fork);
<syntaxhighlight lang="perl">1 while ($_ = shift and @ARGV and !fork);
sleep $_;
sleep $_;
print "$_\n";
print "$_\n";
wait;</lang>
wait;</syntaxhighlight>




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:
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:
<lang Perl>use Coro;
<syntaxhighlight lang="perl">use Coro;
$ret = Coro::Channel->new;
$ret = Coro::Channel->new;
@nums = qw(1 32 2 59 2 39 43 15 8 9 12 9 11);
@nums = qw(1 32 2 59 2 39 43 15 8 9 12 9 11);
Line 1,519: Line 1,519:
}
}


print $ret->get,"\n" for 1..@nums;</lang>
print $ret->get,"\n" for 1..@nums;</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
Based on [[Sorting_algorithms/Sleep_sort#Euphoria|Euphoria]]
Based on [[Sorting_algorithms/Sleep_sort#Euphoria|Euphoria]]
<!--<lang Phix>(notonline)-->
<!--<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: #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: #004080;">integer</span> <span style="color: #000000;">count</span>
Line 1,551: Line 1,551:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</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>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
===Sleeping in main process===
===Sleeping in main process===
<lang PicoLisp>(de sleepSort (Lst)
<syntaxhighlight lang="picolisp">(de sleepSort (Lst)
(make
(make
(for (I . N) Lst
(for (I . N) Lst
Line 1,562: Line 1,562:
(pop 'Lst)
(pop 'Lst)
(task (- I)) ) )
(task (- I)) ) )
(wait NIL (not Lst)) ) )</lang>
(wait NIL (not Lst)) ) )</syntaxhighlight>
===Sleeping in child processes===
===Sleeping in child processes===
<lang PicoLisp>(de sleepSort (Lst)
<syntaxhighlight lang="picolisp">(de sleepSort (Lst)
(make
(make
(for N Lst
(for N Lst
Line 1,571: Line 1,571:
(pop 'Lst)
(pop 'Lst)
(task (close @)) ) )
(task (close @)) ) )
(wait NIL (not Lst)) ) )</lang>
(wait NIL (not Lst)) ) )</syntaxhighlight>
Output in both cases:
Output in both cases:
<pre>: (sleepSort (3 1 4 1 5 9 2 6 5))
<pre>: (sleepSort (3 1 4 1 5 9 2 6 5))
Line 1,577: Line 1,577:
===Just printing (no sorted result list)===
===Just printing (no sorted result list)===
Basically the C code.
Basically the C code.
<lang PicoLisp>(for N (3 1 4 1 5 9 2 6 5)
<syntaxhighlight lang="picolisp">(for N (3 1 4 1 5 9 2 6 5)
(unless (fork)
(unless (fork)
(call 'sleep N)
(call 'sleep N)
(msg N)
(msg N)
(bye) ) )</lang>
(bye) ) )</syntaxhighlight>
Output:
Output:
<pre>1
<pre>1
Line 1,595: Line 1,595:
=={{header|Pike}}==
=={{header|Pike}}==


<syntaxhighlight lang="pike">
<lang Pike>
#!/usr/bin/env pike
#!/usr/bin/env pike
Line 1,617: Line 1,617:
return;
return;
}
}
</syntaxhighlight>
</lang>
Output :
Output :
<pre>
<pre>
Line 1,631: Line 1,631:
=={{header|Prolog}}==
=={{header|Prolog}}==
Works with SWI-Prolog.
Works with SWI-Prolog.
<lang Prolog>sleep_sort(L) :-
<syntaxhighlight lang="prolog">sleep_sort(L) :-
thread_pool_create(rosetta, 1024, []) ,
thread_pool_create(rosetta, 1024, []) ,
maplist(initsort, L, LID),
maplist(initsort, L, LID),
Line 1,640: Line 1,640:
thread_create_in_pool(rosetta, (sleep(V), writeln(V)), Id, []).
thread_create_in_pool(rosetta, (sleep(V), writeln(V)), Id, []).


</syntaxhighlight>
</lang>
Output :
Output :
<pre> sleep_sort([5, 1, 3, 2, 11, 6, 3, 4]).
<pre> sleep_sort([5, 1, 3, 2, 11, 6, 3, 4]).
Line 1,656: Line 1,656:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>NewMap threads()
<syntaxhighlight lang="purebasic">NewMap threads()


Procedure Foo(n)
Procedure Foo(n)
Line 1,672: Line 1,672:
Next
Next
Print("Press ENTER to exit"): Input()
Print("Press ENTER to exit"): Input()
EndIf</lang>
EndIf</syntaxhighlight>
<pre>Sleep_sort.exe 3 1 4 1 5 9
<pre>Sleep_sort.exe 3 1 4 1 5 9
1
1
Line 1,685: Line 1,685:
===Python: Using threading.Timer===
===Python: Using threading.Timer===


<lang python>from time import sleep
<syntaxhighlight lang="python">from time import sleep
from threading import Timer
from threading import Timer


Line 1,704: Line 1,704:
print('sleep sort worked for:',x)
print('sleep sort worked for:',x)
else:
else:
print('sleep sort FAILED for:',x)</lang>
print('sleep sort FAILED for:',x)</syntaxhighlight>


;Sample output:
;Sample output:
Line 1,714: Line 1,714:
could be a sole translation from the original version in Bash:
could be a sole translation from the original version in Bash:
{{Works with|Python 3.5+}}
{{Works with|Python 3.5+}}
<lang python>#!/usr/bin/env python3
<syntaxhighlight lang="python">#!/usr/bin/env python3
from asyncio import run, sleep, wait
from asyncio import run, sleep, wait
from sys import argv
from sys import argv
Line 1,723: Line 1,723:


if __name__ == '__main__':
if __name__ == '__main__':
run(wait(map(f, map(int, argv[1:]))))</lang>
run(wait(map(f, map(int, argv[1:]))))</syntaxhighlight>
Example usage:
Example usage:
<pre>
<pre>
Line 1,740: Line 1,740:
=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 1,756: Line 1,756:
;; outputs '(2 5 5 7 8 9 10)
;; outputs '(2 5 5 7 8 9 10)
(sleep-sort '(5 8 2 7 9 10 5))
(sleep-sort '(5 8 2 7 9 10 5))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)


<lang perl6>await map -> $delay { start { sleep $delay ; say $delay } },
<syntaxhighlight lang="raku" line>await map -> $delay { start { sleep $delay ; say $delay } },
<6 8 1 12 2 14 5 2 1 0>;</lang>
<6 8 1 12 2 14 5 2 1 0>;</syntaxhighlight>


{{out}}
{{out}}
Line 1,778: Line 1,778:
This can also be written using reactive programming:
This can also be written using reactive programming:


<lang perl6>#!/usr/bin/env raku
<syntaxhighlight lang="raku" line>#!/usr/bin/env raku
use v6;
use v6;
react whenever Supply.from-list(@*ARGS).start({ .&sleep // +$_ }).flat { .say }</lang>
react whenever Supply.from-list(@*ARGS).start({ .&sleep // +$_ }).flat { .say }</syntaxhighlight>


{{out}}
{{out}}
Line 1,794: Line 1,794:
This sort will accept any manner of numbers, &nbsp; or for that matter, &nbsp; any character string as well.
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.
<br>REXX isn't particular what is being sorted.
<lang rexx>/*REXX program implements a sleep sort (with numbers entered from the command line (CL).*/
<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! */
numeric digits 300 /*over the top, but what the hey! */
/* (above) ··· from vaudeville. */
/* (above) ··· from vaudeville. */
Line 1,841: Line 1,841:
do m=1 for howMany-1; next= m+1; if @.m>@.next then return 0 /*¬ in 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 youth. */
end /*m*/ /*keep looking for fountain of youth. */
return 1 /*yes, indicate with an indicator. */</lang>
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.
Programming note: &nbsp; this REXX program makes use of &nbsp; '''DELAY''' &nbsp; BIF which delays (sleeps) for a specified amount of seconds.
<br>Some REXXes don't have a &nbsp; '''DELAY''' &nbsp; BIF, &nbsp; so one is included here &nbsp; ──► &nbsp; [[DELAY.REX]].
<br>Some REXXes don't have a &nbsp; '''DELAY''' &nbsp; BIF, &nbsp; so one is included here &nbsp; ──► &nbsp; [[DELAY.REX]].
Line 1,873: Line 1,873:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>require 'thread'
<syntaxhighlight lang="ruby">require 'thread'


nums = ARGV.collect(&:to_i)
nums = ARGV.collect(&:to_i)
Line 1,887: Line 1,887:
threads.each {|t| t.join}
threads.each {|t| t.join}


p sorted</lang>
p sorted</syntaxhighlight>


Example
Example
Line 1,894: Line 1,894:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>use std::thread;
<syntaxhighlight lang="rust">use std::thread;


fn sleepsort<I: Iterator<Item=u32>>(nums: I) {
fn sleepsort<I: Iterator<Item=u32>>(nums: I) {
Line 1,906: Line 1,906:
fn main() {
fn main() {
sleepsort(std::env::args().skip(1).map(|s| s.parse().unwrap()));
sleepsort(std::env::args().skip(1).map(|s| s.parse().unwrap()));
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>$ ./sleepsort 50 34 43 3 2
<pre>$ ./sleepsort 50 34 43 3 2
Line 1,917: Line 1,917:


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>object SleepSort {
<syntaxhighlight lang="scala">object SleepSort {


def main(args: Array[String]): Unit = {
def main(args: Array[String]): Unit = {
Line 1,933: Line 1,933:
}.start())
}.start())


}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<lang bash>$ scala SleepSort 1 3 6 0 9 7 4 2 5 8
<syntaxhighlight 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 </lang>
0 1 2 3 4 5 5 6 7 8 9 </syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>ARGV.map{.to_i}.map{ |i|
<syntaxhighlight lang="ruby">ARGV.map{.to_i}.map{ |i|
{Sys.sleep(i); say i}.fork;
{Sys.sleep(i); say i}.fork;
}.each{.wait};</lang>
}.each{.wait};</syntaxhighlight>
{{out}}
{{out}}
<pre>% sidef test.sf 5 1 3 2 11 6 4
<pre>% sidef test.sf 5 1 3 2 11 6 4
Line 1,953: Line 1,953:


=={{header|Simula}}==
=={{header|Simula}}==
<lang simula>SIMULATION
<syntaxhighlight lang="simula">SIMULATION
BEGIN
BEGIN


Line 1,972: Line 1,972:
OUTIMAGE;
OUTIMAGE;


END;</lang>
END;</syntaxhighlight>
{{out}}
{{out}}
<pre> 1 2 3 3 4 6 7 9
<pre> 1 2 3 3 4 6 7 9
Line 1,979: Line 1,979:
=={{header|SNUSP}}==
=={{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.
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
/$>\ input until eof
#/?<\?,/ foreach: fork
#/?<\?,/ foreach: fork
Line 1,985: Line 1,985:
/:\?-; delay /
/:\?-; delay /
\.# print and exit thread
\.# print and exit thread
</syntaxhighlight>
</lang>


Legend:
Legend:
Line 1,993: Line 1,993:


=={{header|Swift}}==
=={{header|Swift}}==
<lang Swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


for i in [5, 2, 4, 6, 1, 7, 20, 14] {
for i in [5, 2, 4, 6, 1, 7, 20, 14] {
Line 2,004: Line 2,004:
}
}


CFRunLoopRun()</lang>
CFRunLoopRun()</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,019: Line 2,019:
=={{header|Tcl}}==
=={{header|Tcl}}==
===Tcl 8.5===
===Tcl 8.5===
<lang tcl>#!/bin/env tclsh
<syntaxhighlight lang="tcl">#!/bin/env tclsh
set count 0
set count 0
proc process val {
proc process val {
Line 2,032: Line 2,032:
while {$count < $argc} {
while {$count < $argc} {
vwait count
vwait count
}</lang>
}</syntaxhighlight>
'''Demo:'''
'''Demo:'''
<pre>
<pre>
Line 2,052: Line 2,052:
</pre>
</pre>
===Tcl 8.6===
===Tcl 8.6===
<lang tcl>set sorted {}
<syntaxhighlight lang="tcl">set sorted {}
lmap x $argv {after $x [list lappend sorted $x]}
lmap x $argv {after $x [list lappend sorted $x]}
while {[llength $sorted] != $argc} {
while {[llength $sorted] != $argc} {
vwait sorted
vwait sorted
}
}
puts $sorted</lang>
puts $sorted</syntaxhighlight>
{{out}}
{{out}}
<pre>$ echo 'puts [lmap _ [lrepeat 30 {}] {expr {int(rand() * 100)}}]' | tclsh | tee /dev/tty | xargs tclsh sleepsort.tcl
<pre>$ echo 'puts [lmap _ [lrepeat 30 {}] {expr {int(rand() * 100)}}]' | tclsh | tee /dev/tty | xargs tclsh sleepsort.tcl
Line 2,064: Line 2,064:


===Tcl 8.6: coroutine===
===Tcl 8.6: coroutine===
<lang tcl>#! /usr/bin/env tclsh
<syntaxhighlight lang="tcl">#! /usr/bin/env tclsh
package require Tcl 8.6
package require Tcl 8.6
Line 2,100: Line 2,100:
coroutine c sleep-sort [validate $argv] ::sorted
coroutine c sleep-sort [validate $argv] ::sorted
vwait sorted</lang>
vwait sorted</syntaxhighlight>
'''Demo:'''
'''Demo:'''
<pre>
<pre>
Line 2,118: Line 2,118:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|Bourne Shell}}
{{works with|Bourne Shell}}
<lang bash>f() {
<syntaxhighlight lang="bash">f() {
sleep "$1"
sleep "$1"
echo "$1"
echo "$1"
Line 2,127: Line 2,127:
shift
shift
done
done
wait</lang>
wait</syntaxhighlight>
Usage and output:
Usage and output:
<pre>
<pre>
Line 2,140: Line 2,140:


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
<lang vbnet>Imports System.Threading
<syntaxhighlight lang="vbnet">Imports System.Threading


Module Module1
Module Module1
Line 2,158: Line 2,158:
End Sub
End Sub


End Module</lang>
End Module</syntaxhighlight>


{{out}}
{{out}}
Line 2,173: Line 2,173:
=={{header|Wren}}==
=={{header|Wren}}==
More of a simulation than a 'true' sleep sort.
More of a simulation than a 'true' sleep sort.
<lang ecmascript>import "timer" for Timer
<syntaxhighlight lang="ecmascript">import "timer" for Timer
import "io" for Stdout
import "io" for Stdout
import "os" for Process
import "os" for Process
Line 2,202: Line 2,202:
}
}
}
}
System.print()</lang>
System.print()</syntaxhighlight>


{{out}}
{{out}}
Line 2,213: Line 2,213:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>vm.arglist.apply(fcn(n){ Atomic.sleep(n); print(n) }.launch);
<syntaxhighlight lang="zkl">vm.arglist.apply(fcn(n){ Atomic.sleep(n); print(n) }.launch);
Atomic.waitFor(fcn{ vm.numThreads == 1 }); Atomic.sleep(2); println();</lang>
Atomic.waitFor(fcn{ vm.numThreads == 1 }); Atomic.sleep(2); println();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>