Add Elixir examples for quicksort

This commit is contained in:
Evgeny Garlukovich
2018-02-05 22:35:57 +03:00
committed by Aditya Bhargava
parent 687d3fece6
commit 5d965d0b8a
5 changed files with 37 additions and 0 deletions

View File

@@ -0,0 +1 @@
# Cannot be implemented in Elixir, because Elixir has no loops :)

View File

@@ -0,0 +1,6 @@
defmodule Recursive do
def sum([]), do: 0
def sum([head | tail]), do: head + sum(tail)
end
IO.puts(Recursive.sum([1, 2, 3, 4]))

View File

@@ -0,0 +1,6 @@
defmodule Recursive do
def count([]), do: 0
def count([_ | tail]), do: 1 + count(tail)
end
IO.puts(Recursive.count([0, 1, 2, 3, 4, 5]))

View File

@@ -0,0 +1,12 @@
defmodule Recursive do
def max([x]), do: x
def max([head | tail]) do
get_max(head, max(tail))
end
defp get_max(x, y) when x > y, do: x
defp get_max(_, y), do: y
end
IO.puts(Recursive.max([1, 5, 10, 25, 16, 1]))

View File

@@ -0,0 +1,12 @@
defmodule Quicksort do
import Enum, only: [split_with: 2]
def sort(list) when length(list) < 2, do: list
def sort([pivot | tail]) do
{less, greater} = split_with(tail, &(&1 <= pivot))
sort(less) ++ [pivot | sort(greater)]
end
end
IO.inspect(Quicksort.sort([10, 5, 2, 3]))