Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions solutions/elixir/binary-search/1/lib/binary_search.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
defmodule BinarySearch do
@doc """
Searches for a key in the tuple using the binary search algorithm.
It returns :not_found if the key is not in the tuple.
Otherwise returns {:ok, index}.

## Examples

iex> BinarySearch.search({}, 2)
:not_found

iex> BinarySearch.search({1, 3, 5}, 2)
:not_found

iex> BinarySearch.search({1, 3, 5}, 5)
{:ok, 2}

"""

@spec search(tuple, integer) :: {:ok, integer} | :not_found

def search(numbers, key) do
search(numbers, key, 0, tuple_size(numbers) - 1)
end

defp search(_numbers, _key, min, max) when min > max, do: :not_found

defp search(numbers, key, min, max) do
mid = div(min + max, 2)
mid_value = elem(numbers, mid)

cond do
mid_value == key -> {:ok, mid}
key < mid_value -> search(numbers, key, min, mid - 1)
true -> search(numbers, key, mid + 1, max)
end
end
end