Last active
February 10, 2017 08:16
-
-
Save tallakt/3ece42950a6ea5db2d47 to your computer and use it in GitHub Desktop.
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
defmodule Bubble do | |
def sort(list) do | |
do_sort list, {[], false} | |
end | |
defp do_sort([a, b | tail], {acc, _}) when b < a do | |
do_sort [a | tail], {[b | acc], true} | |
end | |
defp do_sort([a | tail], {acc, swapped?}) do | |
do_sort tail, {[a | acc], swapped?} | |
end | |
defp do_sort([], {acc, true}) do | |
do_sort Enum.reverse(acc), {[], false} | |
end | |
defp do_sort([], {acc, _}) do | |
Enum.reverse acc | |
end | |
end | |
ExUnit.start() | |
defmodule Bubble.Test do | |
use ExUnit.Case | |
@numbers [3, 2, 1, 4, 5, 9, 8, 7] | |
test "basic sorting" do | |
assert Enum.sort(@numbers) == Bubble.sort(@numbers) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment