Skip to content

Instantly share code, notes, and snippets.

@codecakes
Last active October 29, 2020 14:42
Show Gist options
  • Select an option

  • Save codecakes/1e6b24218be86e2f599bfb78502bef62 to your computer and use it in GitHub Desktop.

Select an option

Save codecakes/1e6b24218be86e2f599bfb78502bef62 to your computer and use it in GitHub Desktop.
Stack sort using elixir
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment