[erlang-questions] Bubble sort in Erlang

Pierpaolo Bernardi olopierpa@REDACTED
Sun May 20 06:46:35 CEST 2007


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.



More information about the erlang-questions mailing list