How to resolve the algorithm Sorting algorithms/Sleep sort step by step in the Tcl programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Sleep sort step by step in the Tcl programming language
Table of Contents
Problem Statement
In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time. Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required. Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sorting algorithms/Sleep sort step by step in the Tcl programming language
Source code in the tcl programming language
#!/bin/env tclsh
set count 0
proc process val {
puts $val
incr ::count
}
# Schedule the output of the values
foreach val $argv {
after [expr {$val * 10}] [list process $val]
}
# Run event loop until all values output...
while {$count < $argc} {
vwait count
}
set sorted {}
lmap x $argv {after $x [list lappend sorted $x]}
while {[llength $sorted] != $argc} {
vwait sorted
}
puts $sorted
#! /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
You may also check:How to resolve the algorithm Isqrt (integer square root) of X step by step in the MAD programming language
You may also check:How to resolve the algorithm Horner's rule for polynomial evaluation step by step in the Octave programming language
You may also check:How to resolve the algorithm Fibonacci sequence step by step in the ERRE programming language
You may also check:How to resolve the algorithm Percolation/Site percolation step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Add a variable to a class instance at runtime step by step in the Tcl programming language