[erlang-questions] Bubble sort in Erlang

andrew cooke andrew@REDACTED
Sun May 20 20:20:41 CEST 2007


sorry, but since this is for someone asking how best to program - using 0
and 1 to signal state (as below) is poor style.  in erlang you can use
"atoms" for this (they can be matched in patterns and assigned to
variables just like any other simple type), and something like "clean" and
"swapped" makes the code easier to read

so you would have sort(L) -> sort(L, [], clean) for example.

andrew


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





More information about the erlang-questions mailing list