Last Updated: February 25, 2016
·
642
· gowind

Bubblesort in Erlang

Bubblesort is pretty non-intuitive in Erlang with its lists and recursive style of programming . Overnight I wrote a bubblesort function in erlang based on the example provided here
http://tinyurl.com/bng9ku2 ( link to a pdf with exercises in erlang)

The code is given as below

 %the func prototype exposed 
 bubblesort(Alist,N) -> bubblesort([],Alist,0,N).
 %all items are sorted
bubblesort(Curlist,Alist,X,N) when X == N -> Alist;
%only largest item is in the temp list. In that case move it to the
%mainlist and proceed with the next item 
%(akin to i++ in the outerloop in C)
bubblesort(Curlist,[H],X,N) -> bubblesort( [], Curlist ++ [H] , X+1,N);
% a[i] > a[j] . Swap them 
bubblesort(Curlist,[A,B|T],X,N) when A > B -> bubblesort(Curlist ++ [B] , [ A |T ] , X,N);
 %a[i] <= a[j] . append a[i] to the temp list
 bubblesort(Curlist,[A,B|T],X,N) -> bubblesort(Curlist ++ [A] , [ B | T] , X ,N).

Note
I used [Somelist] ++ [Someitem] which can be costly when somelist is very large . It is advised not to use it although I did here as I couldnt find any other way