Skip to content

Instantly share code, notes, and snippets.

@sdebnath
Created March 15, 2015 22:38
Show Gist options
  • Save sdebnath/25d13bcbe9feb9b935b1 to your computer and use it in GitHub Desktop.
Save sdebnath/25d13bcbe9feb9b935b1 to your computer and use it in GitHub Desktop.
Quicksort in Erlang
%%==============================================================================
%% Quicksort implementation in Erlang
%%
%% Author: Shawn Debnath
%%==============================================================================
%%----------------------------------------------------------------------
%% qsort_r/1
%%
%% Recursive quicksort
%%----------------------------------------------------------------------
qsort_r([]) ->
[];
qsort_r([Pivot | L]) ->
qsort_r([X || X <- L, X < Pivot]) ++
[Pivot] ++
qsort_r([X || X <- L, X >= Pivot]).
%%----------------------------------------------------------------------
%% qsort/1
%%
%% Tail recursive quicksort
%%----------------------------------------------------------------------
qsort([]) ->
[];
qsort([H | _] = List) ->
{L, E, G} = partition(H, List, {[], [], []}),
qsort(L) ++ E ++ qsort(G).
partition(_, [], {L, E, G}) ->
{L, E, G};
partition(Pivot, [H | List], {L, E, G}) when Pivot > H ->
partition(Pivot, List, {[H | L], E, G});
partition(Pivot, [H | List], {L, E, G}) when Pivot < H ->
partition(Pivot, List, {L, E, [H | G]});
partition(Pivot, [H | List], {L, E, G}) when Pivot == H ->
partition(Pivot, List, {L, [H | E], G}).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment