Skip to content

Instantly share code, notes, and snippets.

@siburu
Created January 31, 2011 16:43
Show Gist options
  • Save siburu/804330 to your computer and use it in GitHub Desktop.
Save siburu/804330 to your computer and use it in GitHub Desktop.
qsort in Erlang
-module(qsort).
-export([qsort/1]).
% qsort/1
qsort([]) -> [];
qsort([Head|Rest]) ->
{Less,Geq} = partition(Rest,Head),
concat(qsort(Less), Head, qsort(Geq)).
% partition/2
partition(List,Pivot) ->
partition(List,Pivot,[],[]).
partition([],_,Less,Geq) -> {Less, Geq};
partition([Head|Rest],Pivot,Less,Geq) when Head < Pivot ->
partition(Rest,Pivot,[Head|Less],Geq);
partition([Head|Rest],Pivot,Less,Geq) ->
partition(Rest,Pivot,Less,[Head|Geq]).
% concat/3
concat(Less,Pivot,Geq) ->
concat(reverse(Less), [Pivot|Geq]).
concat([],Acc) -> Acc;
concat([Head|Rest],Acc) -> concat(Rest, [Head|Acc]).
% reverse/1
reverse(List) -> reverse(List,[]).
reverse([],Acc) -> Acc;
reverse([Head|Rest],Acc) -> reverse(Rest,[Head|Acc]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment