Skip to content

Instantly share code, notes, and snippets.

@rugyoga
Created December 21, 2023 21:48
Show Gist options
  • Save rugyoga/3ca21d4bcc6ec8f295b761d72d73038e to your computer and use it in GitHub Desktop.
Save rugyoga/3ca21d4bcc6ec8f295b761d72d73038e to your computer and use it in GitHub Desktop.
mergesort
defmodule People do
@people ["Mary","John","Emma"]
@heights [180,165,170]
def sort_heights(names, heights) do
heights
|> Enum.zip(names)
|> mergesort()
|> Enum.unzip()
|> elem(1)
end
def merge([], ys), do: ys
def merge(xs, []), do: xs
def merge([x | xs] = l1, [y | ys] = l2) do
if x >= y do
[x | merge(xs, l2)]
else
[y | merge(l1, ys)]
end
end
def mergesort(xs) do
n = length(xs)
if n == 1 do
xs
else
{xs, ys} = Enum.split(xs, div(n, 2))
merge(mergesort(xs), mergesort(ys))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment