Skip to content

Instantly share code, notes, and snippets.

@pstephens
Created October 9, 2014 01:24
Show Gist options
  • Save pstephens/5324cd09c6dc8a97ca0d to your computer and use it in GitHub Desktop.
Save pstephens/5324cd09c6dc8a97ca0d to your computer and use it in GitHub Desktop.
Naive qsort in Erlang.
-module(sort).
-export([qsort/1]).
%%% A slightly naive implementation. But at least it does partial TCO.
partition(_, [], Smaller, Equal, Larger) -> {Smaller, Equal, Larger};
partition(Pivot, [H|T], Smaller, Equal, Larger) when H < Pivot -> partition(Pivot, T, [H|Smaller], Equal, Larger);
partition(Pivot, [H|T], Smaller, Equal, Larger) when H =:= Pivot -> partition(Pivot, T, Smaller, [H|Equal], Larger);
partition(Pivot, [H|T], Smaller, Equal, Larger) when H > Pivot -> partition(Pivot, T, Smaller, Equal, [H|Larger]).
qsort(L) -> qsort(L, []).
qsort([], Acc) -> Acc;
qsort([H|T], Acc) ->
{A,B,C} = partition(H,T,[],[H],[]),
qsort(A, B ++ qsort(C, Acc)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment