Created
October 9, 2014 01:24
-
-
Save pstephens/5324cd09c6dc8a97ca0d to your computer and use it in GitHub Desktop.
Naive qsort in Erlang.
This file contains hidden or 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(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