defmodule StackSort do
@moduledoc """
Documentation for StackSort.
Recursively pops and compares all values with top
of the stack value and pushes it else keeps
popping out until invariant satisfied.
You will find only comments in docstrings.
I(t's a no brainer.
l = [2,300, -100, -1, 0, 1000]
StackSort.sort_stack(l) |> IO.inspect
[-100, -1, 0, 2, 300, 1000]
"""
defp top_stack(stack, top_val), do: [top_val] ++ stack
def sort_stack([]), do: []
@doc """
Pushes greater value i.e. top_val to stack;
"""
def sort_stack([ h | t ]) do
sort_stack(t) |> _insert(h)
end
defp _insert([], top_val), do: [top_val]
defp _insert([ h | t ], top_val) when top_val > h do
t |> _insert(top_val) |> top_stack(h)
end
defp _insert(stack, top_val), do: stack |> top_stack(top_val)
end
l = [2,300, -100, -1, 0, 1000]
StackSort.sort_stack(l) |> IO.inspect
view raw stack_sort.ex hosted with ❤ by GitHub