Last active
October 26, 2017 16:47
-
-
Save SadPandaBear/12264a8297ba26b1e08583d085492c4a to your computer and use it in GitHub Desktop.
Sort Algorithms impl with Elixir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Bubble sort | |
defmodule Bubble do | |
def sort([]), do: [] | |
def sort(l) do | |
round = swap_itr(l) | |
cond do | |
round == l -> l | |
true -> sort(round) | |
end | |
end | |
defp swap_itr([x | []]), do: [x] | |
defp swap_itr([f | [s | r]]) do | |
cond do | |
f < s -> [f | swap_itr([s | r])] | |
true -> [s | swap_itr([f | r])] | |
end | |
end | |
end | |
# Insertion sort | |
defmodule Insertion do | |
def sort(list) when is_list(list), do: sort(list, []) | |
def sort([], sorted), do: sorted | |
def sort([h | t], sorted), do: sort(t, insert(h, sorted)) | |
defp insert(x, []), do: [x] | |
defp insert(x, sorted) when x < hd(sorted), do: [x | sorted] | |
defp insert(x, [h | t]), do: [h | insert(x, t)] | |
end | |
# Is this Insertion sort? | |
# | |
#defmodule Insertion do | |
# def sort([]), do: [] | |
# def sort(l, index \\ 0) do | |
# [f | [s | r]] = l | |
# cond do | |
# f > s and index < length(l) -> sort(swap_index([f |[s | r]]), index + 1) | |
# true -> l | |
# end | |
# end | |
# | |
# def swap_index([x | []]), do: [x] | |
# def swap_index([f | [s | r]]) do | |
# cond do | |
# f < s -> [f | swap_index([s | r])] | |
# true -> [s | swap_index([f | r])] | |
# end | |
# end | |
#end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment