Initial Commit

This commit is contained in:
2024-12-24 17:45:52 +01:00
commit c30845575a
42 changed files with 870 additions and 0 deletions

25
binary.exs Normal file
View File

@@ -0,0 +1,25 @@
defmodule BinarySearch do
def binary_search(_numbers, _key, low, high) when low > high do
:not_found
end
@spec binary_search(list, integer, integer, integer) :: integer | :not_found
def binary_search(numbers, key, low, high) do
md = low + Integer.floor_div(high-low, 2)
IO.inspect(md)
case elem(numbers, md) do
x when x > key -> binary_search(numbers, key, low, md-1)
x when x < key -> binary_search(numbers, key, md+1, high)
x when x == key -> md
end
end
@spec search(tuple, integer) :: {:ok, integer} | :not_found
def search(numbers, key) do
case binary_search(numbers, key, 0, tuple_size(numbers)-1) do
:not_found -> :not_found
x -> {:ok, x}
end
end
end