Created
July 15, 2015 18:21
-
-
Save ntalbott/b4095f4ad31a4dbf3215 to your computer and use it in GitHub Desktop.
Using case
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(list) do | |
case list do | |
[] -> [] | |
[e] -> [e] | |
_ -> | |
{left, right} = Enum.split(list, div(Enum.count(list), 2)) | |
merge(msort(left), msort(right)) | |
end | |
end | |
def merge(left, right) do | |
case {left, right} do | |
{left, []} -> left | |
{[], right} -> right | |
_ -> | |
[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 | |
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