Skip to content

Instantly share code, notes, and snippets.

@epfahl
Created March 2, 2024 12:51
Show Gist options
  • Save epfahl/e1317cdeb59a84bd75c6b1073e0d09e0 to your computer and use it in GitHub Desktop.
Save epfahl/e1317cdeb59a84bd75c6b1073e0d09e0 to your computer and use it in GitHub Desktop.
Quicksort in Elixir
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