[erlang-questions] Bubble sort in Erlang

Milen Dzhumerov gamehack@REDACTED
Sat May 19 18:27:15 CEST 2007


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? I think FP really hit my head - that's the  
first time I've tried any functional programming. The hardest part  
for me was (and still is) maintaining and mutating the state (like  
whether a swap has occurred). So I thought because I have to use  
recursion instead of iteration, I could maintain the state using  
parameter passing. Here it goes, my first Erlang toy program:

-module(bsort).
-export([bubble_sort/1, bstage/1, bstage/2]).

bubble_sort([A,B|Tail]) when Tail =/= [] ->
	{Status, List} = bstage([A,B|Tail]),
	case Status of
		sorted -> List;
		not_sorted -> bubble_sort(List)
	end;
bubble_sort([A,B]) ->
	if
		A > B -> [B, A];
		true -> [A, B]
	end;
bubble_sort([A]) -> [A];
bubble_sort([]) -> [].

bstage(L) ->
	{Swapped, List} = bstage(L, false),
	case Swapped of
		false -> {sorted, List};
		true -> {not_sorted, List}
	end.

bstage([A,B|Tail], Swapped) when Tail =/= [] ->
	if
		A > B -> {_, List1} = bstage([A|Tail], true),
				{true, [B] ++ List1};
		true -> {Swap, List} = bstage([B|Tail], Swapped),
				{Swap, [A] ++ List}
	end;
bstage([A,B], Swapped) ->
	if
		A > B -> {true, [B,A]};
		true -> {Swapped, [A,B]}
	end.

Any comments are greatly appreciated.

Kind regards,
Milen






More information about the erlang-questions mailing list