Created
July 15, 2015 18:15
-
-
Save ntalbott/7384c189f1bfc9d35bf6 to your computer and use it in GitHub Desktop.
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
defmodule MSort do | |
def msort([]), do: [] | |
def msort([e]), do: [e] | |
def msort(list) do | |
{left, right} = Enum.split(list, div(Enum.count(list), 2)) | |
merge(msort(left), msort(right)) | |
end | |
def merge(left, []), do: left | |
def merge([], right), do: right | |
def merge(left, right) do | |
[left_head | left_rest] = left | |
[right_head | right_rest] = right | |
if left_head < right_head do | |
[left_head | merge(left_rest, right)] | |
else | |
[right_head | merge(right_rest, left)] | |
end | |
end | |
end | |
IO.puts(inspect MSort.msort([3,5,2,7])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment