Skip to content

Instantly share code, notes, and snippets.

@ntalbott
Created July 15, 2015 18:21
Show Gist options
  • Save ntalbott/b4095f4ad31a4dbf3215 to your computer and use it in GitHub Desktop.
Save ntalbott/b4095f4ad31a4dbf3215 to your computer and use it in GitHub Desktop.
Using case
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