Sorting algorithms/Sleep sort: Difference between revisions
Content added Content deleted
m (→Python: Using threading.Timer: Whoops.) |
(add Tcl 8.6 version with coroutine) |
||
Line 1,659: | Line 1,659: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
===Tcl 8.5=== |
|||
<lang tcl>#!/bin/env tclsh |
<lang tcl>#!/bin/env tclsh |
||
set count 0 |
set count 0 |
||
Line 1,673: | Line 1,674: | ||
vwait count |
vwait count |
||
}</lang> |
}</lang> |
||
'''Demo:''' |
|||
Demonstrating: |
|||
<pre> |
<pre> |
||
bash$ sleepsort.tcl 3 1 4 5 2 3 1 6 1 3 2 5 4 6 |
bash$ sleepsort.tcl 3 1 4 5 2 3 1 6 1 3 2 5 4 6 |
||
Line 1,690: | Line 1,691: | ||
6 |
6 |
||
6 |
6 |
||
</pre> |
|||
===Tcl 8.6: coroutine=== |
|||
<lang tcl>#! /usr/bin/env tclsh |
|||
package require Tcl 8.6 |
|||
# By aspect (https://wiki.tcl-lang.org/page/aspect). Modified slightly. |
|||
# 1. Schedule N delayed calls to our own coroutine. |
|||
# 2. Yield N times to grab the scheduled values. Print each. |
|||
# 3. Store the sorted list in $varName. |
|||
proc sleep-sort {ls varName} { |
|||
foreach x $ls { |
|||
after $x [info coroutine] $x |
|||
} |
|||
set $varName [lmap x $ls { |
|||
set newX [yield] |
|||
puts $newX |
|||
lindex $newX |
|||
}] |
|||
} |
|||
# Ensure the list is suitable for use with [sleep-sort]. |
|||
proc validate ls { |
|||
if {[llength $ls] == 0} { |
|||
error {list is empty} |
|||
} |
|||
foreach x $ls { |
|||
if {![string is integer -strict $x] || $x < 0} { |
|||
error [list invalid value: $x] |
|||
} |
|||
} |
|||
return $ls |
|||
} |
|||
coroutine c sleep-sort [validate $argv] ::sorted |
|||
vwait sorted</lang> |
|||
'''Demo:''' |
|||
<pre> |
|||
$ ./sleepsort.tcl 1 2 100 40 76 0 0 0 200 199 |
|||
0 |
|||
0 |
|||
0 |
|||
1 |
|||
2 |
|||
40 |
|||
76 |
|||
100 |
|||
199 |
|||
200 |
|||
</pre> |
</pre> |
||