Skip to content

Instantly share code, notes, and snippets.

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