Skip to content

Commit 39ceb66

Browse files
committed
Add Quick Sort in Elixir
1 parent 63e770e commit 39ceb66

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

archive/e/elixir/quick-sort.ex

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
defmodule QuickSort do
2+
@doc """
3+
Sorts a list of integers in ascending order using the quicksort algorithm.
4+
"""
5+
@spec quick_sort(list :: list(integer())) :: list(integer())
6+
def quick_sort([]), do: []
7+
8+
def quick_sort([x | xs]) do
9+
{left, right} = Enum.split_with(xs, &(&1 < x))
10+
quick_sort(left) ++ [x] ++ quick_sort(right)
11+
end
12+
13+
@spec parse_list(str :: String.t()) :: {:ok, list(integer())} | :error
14+
def parse_list(""), do: :error
15+
16+
def parse_list(str) do
17+
str
18+
|> String.split(",")
19+
|> Enum.map(&String.trim/1)
20+
|> Enum.reduce_while({:ok, []}, fn n, {:ok, acc} ->
21+
case Integer.parse(n) do
22+
{n, ""} -> {:cont, {:ok, [n | acc]}}
23+
_ -> {:halt, :error}
24+
end
25+
end)
26+
end
27+
end
28+
29+
with [arg] <- System.argv(),
30+
{:ok, [_, _ | _] = list} <- QuickSort.parse_list(arg) do
31+
QuickSort.quick_sort(list) |> Enum.join(", ") |> IO.puts()
32+
else
33+
_ ->
34+
IO.puts(
35+
"Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""
36+
)
37+
end

0 commit comments

Comments
 (0)