I think the more interesting solutions are deeper in the thread mainly #43, #44, #83.
Mostly just for fun but its neat to see an Erlang solution since this should be right up its alley.
Mostly just for fun but its neat to see an Erlang solution since this should be right up its alley.
-module(sleepsort).
-export([sort/2, spawn_waiters/3, wait/4]).
sort(Xs, Conv) ->
spawn(?MODULE, spawn_waiters, [Xs, Conv, self()]),
receive
{spawned, N} -> queue(N)
end.
queue(N) -> queue(N, []).
queue(0, Xs) ->
lists:reverse(Xs);
queue(N, Xs) ->
receive
{item, X} ->
queue(N - 1, [X|Xs])
end.
spawn_waiters(Xs, Conv, P) -> spawn_waiters(P, Conv, Xs, 0).
spawn_waiters(P, _, [], N) ->
P ! {spawned, N};
spawn_waiters(P, Conv, [X|Xs], N) ->
spawn(?MODULE, wait, [X, Conv(X), P, self()]),
receive
monitored -> ok
end,
spawn_waiters(P, Conv, Xs, N + 1).
wait(X, T, Q, P) ->
Ref = erlang:monitor(process, P),
P ! monitored,
receive
{'DOWN', Ref, process, P, _} -> ok
end,
timer:sleep(T),
Q ! {item, X}.
Edit: finally got the formatting right. var numbers = process.argv.slice(2)
, output = []
, negative = []
for (var i=0, ln=numbers.length; i<ln; i++){
var n = +numbers[i]
setTimeout((function(n){ return function(){
if (n<0) negative.unshift(n)
else output.push(n)
if (output.length + negative.length === numbers.length) {
return console.log(negative.concat(output))
}
}})(n), Math.abs(n)/1000)
}
Works with negative numbers. $ node sleepsort -2 1 0.1 4 -1 7 -3 9
[ -3, -2, -1, 0.1, 1, 4, 7, 9 ] function sleep_sort (inputs) {
function child (number) {
setTimeout(function () {console.log(number)}, Math.pow(2,number))
}
for (var i = 0; i < inputs.length; ++i)
child(inputs[i])
}
sleep_sort(process.argv.slice(2));