Created
December 21, 2023 21:48
-
-
Save rugyoga/3ca21d4bcc6ec8f295b761d72d73038e to your computer and use it in GitHub Desktop.
mergesort
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 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