From d7a63614bdfb2a3113c199ee726ffd690202e954 Mon Sep 17 00:00:00 2001 From: "exercism-solutions-syncer[bot]" <211797793+exercism-solutions-syncer[bot]@users.noreply.github.com> Date: Thu, 15 Jan 2026 01:20:41 +0000 Subject: [PATCH] [Sync Iteration] elixir/binary-search/1 --- .../binary-search/1/lib/binary_search.ex | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 solutions/elixir/binary-search/1/lib/binary_search.ex diff --git a/solutions/elixir/binary-search/1/lib/binary_search.ex b/solutions/elixir/binary-search/1/lib/binary_search.ex new file mode 100644 index 0000000..c177fba --- /dev/null +++ b/solutions/elixir/binary-search/1/lib/binary_search.ex @@ -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