<br><span style="font-family: courier new,monospace;">-module(bubble).</span><br style="font-family: courier new,monospace;"><span style="font-family: courier new,monospace;">-export([sort/1]).</span><br style="font-family: courier new,monospace;">
<br style="font-family: courier new,monospace;"><span style="font-family: courier new,monospace;">sort(L) -> sort(L, [], 0).</span><br style="font-family: courier new,monospace;"><br style="font-family: courier new,monospace;">
<span style="font-family: courier new,monospace;">sort([], R, 0) -> lists:reverse(R);</span><br style="font-family: courier new,monospace;"><span style="font-family: courier new,monospace;">sort([], R, 1) -> sort(lists:reverse(R));
</span><br style="font-family: courier new,monospace;"><span style="font-family: courier new,monospace;">sort([A], R, S) -> sort([], [A|R], S);</span><br style="font-family: courier new,monospace;"><span style="font-family: courier new,monospace;">
sort([A,B|T], R, _) when A>B -> sort([A|T], [B|R], 1);</span><br style="font-family: courier new,monospace;"><span style="font-family: courier new,monospace;">sort([A,B|T], R, S) -> sort([B|T], [A|R], S).</span><br style="font-family: courier new,monospace;">
<br style="font-family: courier new,monospace;"><br><div><span class="gmail_quote">On 5/20/07, <b class="gmail_sendername">Pierpaolo Bernardi</b> <<a href="mailto:olopierpa@gmail.com">olopierpa@gmail.com</a>> wrote:
</span><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">On 5/19/07, Milen Dzhumerov <<a href="mailto:gamehack@gmail.com">gamehack@gmail.com
</a>> wrote:<br>> Hi all,<br>><br>> I've recently picked up the "Programming Erlang" book and started<br>> experimenting with Erlang. So I wanted to implement some toy<br>> algorithms - would you believe me that I was kind of stuck for
<br>> several days on the train while going to work implementing a simple<br>> bubble sort algorithm?<br><br>The following is the most straightforward implementation of bubblesort<br>I could come up with:<br><br>%%%%
<br>-module(bubble).<br><br>-export([sort/1]).<br><br>sort(List) -><br>    case bubble_pass(List) of<br>        {Res,true} -> Res;<br>        {Res,false} -> sort(Res)<br>    end.<br><br><br>%% bubble_pass(List) -> {Bubbled,Done}.
<br><br>bubble_pass([]) -><br>    {[],true};<br>bubble_pass([A]) -><br>    {[A],true};<br>bubble_pass([A|Rest]) -><br>    {[B|T],Done} = bubble_pass(Rest),<br>    if A =< B -><br>            {[A,B|T],Done};
<br>       true -><br>            {[B,A|T],false}<br>    end.<br><br>%%%%<br><br>Cheers<br>P.<br>_______________________________________________<br>erlang-questions mailing list<br><a href="mailto:erlang-questions@erlang.org">
erlang-questions@erlang.org</a><br><a href="http://www.erlang.org/mailman/listinfo/erlang-questions">http://www.erlang.org/mailman/listinfo/erlang-questions</a><br></blockquote></div><br>