Created
March 14, 2013 20:04
-
-
Save apauley/5164716 to your computer and use it in GitHub Desktop.
Erlang version of sleep sort based on http://dis.4chan.org/read/prog/1295544154 http://instacod.es/65572 http://xkcd.com/1185/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(sleepsort). | |
-export([test/0, | |
sort/1]). | |
test() -> | |
[1,2,3] = sort([1,2,3]), | |
[1,2,3] = sort([2,1,3]), | |
[] = sort([]), | |
[2,4,8,12,19] = sort([19,8,4,12,2]), | |
Seq100 = lists:seq(1,100), | |
Seq100 = sort(lists:reverse(Seq100)), | |
ok. | |
sort(List) -> | |
F = fun(Int) -> | |
Self = self(), | |
spawn(fun() -> sleepsend(Self, Int) end) | |
end, | |
lists:foreach(F, List), | |
receive_sort(List, []). | |
receive_sort([], Sorted) -> | |
lists:reverse(Sorted); | |
receive_sort([_H|T], Acc) -> | |
receive | |
{elem, Int} -> | |
receive_sort(T, [Int|Acc]) | |
after 60000 -> | |
{error, timeout} | |
end. | |
sleepsend(From, Int) when is_integer(Int) -> | |
timer:sleep(Int), | |
From ! {elem, Int}, | |
ok. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment