Skip to content

Instantly share code, notes, and snippets.

@GoWind
Last active January 2, 2016 09:29
Show Gist options
  • Save GoWind/8283404 to your computer and use it in GitHub Desktop.
Save GoWind/8283404 to your computer and use it in GitHub Desktop.
Bubble Sort 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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment