Last active
December 14, 2015 03:28
-
-
Save stolen/5020822 to your computer and use it in GitHub Desktop.
Recursive bubble sort in Erlang (just for fun)
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
-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