Skip to content

Instantly share code, notes, and snippets.

@stolen
Last active December 14, 2015 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stolen/5020822 to your computer and use it in GitHub Desktop.
Save stolen/5020822 to your computer and use it in GitHub Desktop.
Recursive bubble sort in Erlang (just for fun)
-module(bubble).
-export([sort/1, sort/2]).
sort(List) ->
sort(fun erlang:'=<'/2, List, []).
sort(Compare, List) ->
sort(Compare, List, []).
% Pop bubble from input, push it to correct position in tail, than repeat until no bubbles left
sort(Compare, [Bubble|Bubbles], SortedTail) ->
Sorted = push_bubble(Compare, Bubble, SortedTail),
sort(Compare, Bubbles, Sorted);
sort(_Compare, [], Sorted) ->
Sorted.
% while bubble compares after head, continue pushing
push_bubble(Compare, Bubble, [Hd|Tail] = List) ->
case Compare(Bubble, Hd) of
true -> [Bubble|List];
false -> [Hd|push_bubble(Compare, Bubble, Tail)]
end;
push_bubble(_Compare, Bubble, []) ->
% Termination
[Bubble].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment