[erlang-questions] Bubble sort in Erlang
Mark Scandariato
mark@REDACTED
Sun May 20 18:32:29 CEST 2007
-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
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20070520/de5733be/attachment.htm>
More information about the erlang-questions
mailing list