Created
March 15, 2015 22:38
-
-
Save sdebnath/25d13bcbe9feb9b935b1 to your computer and use it in GitHub Desktop.
Quicksort in Erlang
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
%%============================================================================== | |
%% 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