Created
March 2, 2024 12:51
-
-
Save epfahl/e1317cdeb59a84bd75c6b1073e0d09e0 to your computer and use it in GitHub Desktop.
Quicksort in Elixir
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 Quicksort do | |
@spec sort([any()], :asc | :desc) :: [any()] | |
def sort(values, direction \\ :asc) do | |
sorted = sort(values) | |
if direction == :asc do | |
sorted | |
else | |
Enum.reverse(sorted) | |
end | |
end | |
# Sort the list in ascending order | |
defp sort([], _dir), do: [] | |
defp sort([x], _dir), do: [x] | |
defp sort([p | rest], dir) do | |
# Partition `rest` in a single pass | |
{lesser, greater} = | |
Enum.reduce(rest, {[p], []}, fn x, {left, right} -> | |
if x < p do | |
{[x | left], right} | |
else | |
{left, [x | right]} | |
end | |
end) | |
Enum.concat(sort(left), sort(right)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment