Sorting algorithms/Sleep sort: Difference between revisions
Content added Content deleted
(add dart implementation) |
(→{{header|Lua}}: Add implementation) |
||
Line 587: | Line 587: | ||
9 |
9 |
||
</pre> |
</pre> |
||
=={{header|Lua}}== |
|||
Here's a slow implementation using only stock C Lua: |
|||
<lang lua>function sleeprint(n) |
|||
local t0 = os.time() |
|||
while os.time() - t0 <= n do |
|||
coroutine.yield(false) |
|||
end |
|||
print(n) |
|||
return true |
|||
end |
|||
coroutines = {} |
|||
for i=1, #arg do |
|||
wrapped = coroutine.wrap(sleeprint) |
|||
table.insert(coroutines, wrapped) |
|||
wrapped(tonumber(arg[i])) |
|||
end |
|||
done = false |
|||
while not done do |
|||
done = true |
|||
for i=#coroutines,1,-1 do |
|||
if coroutines[i]() then |
|||
table.remove(coroutines, i) |
|||
else |
|||
done = false |
|||
end |
|||
end |
|||
end</lang> |
|||
By installing LuaSocket, you can get better than 1-second precision on the clock, and therefore faster output: |
|||
<lang lua>socket = require 'socket' |
|||
function sleeprint(n) |
|||
local t0 = socket.gettime() |
|||
while (socket.gettime() - t0)*100 <= n do |
|||
coroutine.yield(false) |
|||
end |
|||
print(n) |
|||
return true |
|||
end |
|||
coroutines = {} |
|||
for i=1, #arg do |
|||
wrapped = coroutine.wrap(sleeprint) |
|||
table.insert(coroutines, wrapped) |
|||
wrapped(tonumber(arg[i])) |
|||
end |
|||
done = false |
|||
while not done do |
|||
done = true |
|||
for i=#coroutines,1,-1 do |
|||
if coroutines[i]() then |
|||
table.remove(coroutines, i) |
|||
else |
|||
done = false |
|||
end |
|||
end |
|||
end</lang> |
|||
=={{header|Mathematica}}== |
=={{header|Mathematica}}== |