Skip to content

Instantly share code, notes, and snippets.

@ian-plosker
Created June 8, 2011 20:27
Show Gist options
  • Save ian-plosker/1015319 to your computer and use it in GitHub Desktop.
Save ian-plosker/1015319 to your computer and use it in GitHub Desktop.
Erlang Bubble Sort
-module(bubble_sort).
-export([bubble_sort/1, bubble_sort/2]).
-spec bubble_sort(list(T)) -> list(T).
bubble_sort(L) ->
bubble_sort(L, fun(A, B) ->
case A > B of
true -> greater_than;
false ->
case A =:= B of
true -> equal_to;
false -> less_than
end
end
end).
-spec bubble_sort(list(T), fun((T, T) -> greater_than | less_than | equal_to)) -> list(T).
bubble_sort([], _C) -> [];
bubble_sort([_] = L, _C) -> L;
bubble_sort(L1, C) ->
case bubble_sort(L1, C, false) of
{L2, true} -> bubble_sort(L2, C);
{L2, false} -> L2
end.
bubble_sort([], _C, MovedElement) -> { [], MovedElement };
bubble_sort([_] = L, _C, MovedElement) -> { L, MovedElement };
bubble_sort([A, B | R], C, MovedElement) ->
case C(A, B) of
greater_than ->
{Rest, _} = bubble_sort([A | R], C, MovedElement),
{[B | Rest], true};
_ ->
{Rest, MovedElement1} = bubble_sort([B | R], C, MovedElement),
{[A | Rest], MovedElement1}
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment