Skip to content

Instantly share code, notes, and snippets.

@jepio
Last active August 29, 2015 14:02
Show Gist options
  • Save jepio/e0e5139858a8d28849d8 to your computer and use it in GitHub Desktop.
Save jepio/e0e5139858a8d28849d8 to your computer and use it in GitHub Desktop.
A/The quicksort implementation in erlang. What a fun language.
-module(qsort).
-export([sort/1,start/0,part/2,qsort/1]).
%% usage: erlc qsort.erl && erl -run qsort -run init stop -noshell
%% easiest way to write a quick sort %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
sort([Pivot|T]) ->
sort([ X || X <- T, X < Pivot]) ++
[Pivot|[Pivot|| X <- T,X == Pivot]] ++
sort([ X || X <- T, X > Pivot]);
sort([]) -> [].
%%%%
%% quick sort with partitioning %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
qsort([]) -> [];
qsort([Pivot|T]) ->
{L,E,G} = part(Pivot,T),
qsort(L) ++ E ++ qsort(G).
%% partitioning
part(Pivot,T) ->
part(Pivot,T,{[],[Pivot],[]}).
part(_,[],{L,E,G}) -> {L,E,G};
part(Pivot,[H|T],{L,E,G}) ->
if
H > Pivot ->
part(Pivot,T,{L,E,[H|G]});
H < Pivot ->
part(Pivot,T,{[H|L],E,G});
H == Pivot ->
part(Pivot,T,{L,[H|E],G})
end.
%%%%
%% runnable testing function %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
start() ->
random:seed(now()),
N = 100000,
%% Probably the best way to generate a random sequence
List = [random:uniform(N) || _ <- lists:seq(1,N)],
{Time,_} = timer:tc(qsort,sort,[List]),
io:format("No partition ~p s~n",[Time/1000000]),
{Time2,_} = timer:tc(qsort,qsort,[List]),
io:format("Partition ~p s~n",[Time2/1000000]).
@jepio
Copy link
Author

jepio commented Jun 19, 2014

To use the functions launch erl, compile with c(qsort). and then sort by executing qsort:sort([5,4,3,2]). or qsort:qsort([5,4,3,2]).. Never forget the dot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment