Last active
August 29, 2015 14:02
-
-
Save jepio/e0e5139858a8d28849d8 to your computer and use it in GitHub Desktop.
A/The quicksort implementation in erlang. What a fun language.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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]). | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use the functions launch
erl
, compile withc(qsort).
and then sort by executingqsort:sort([5,4,3,2]).
orqsort:qsort([5,4,3,2]).
. Never forget the dot.