From 088c9de6c110dfcd468f5491c1038fdb9d6cf39f Mon Sep 17 00:00:00 2001 From: "exercism-solutions-syncer[bot]" <211797793+exercism-solutions-syncer[bot]@users.noreply.github.com> Date: Thu, 14 Aug 2025 12:42:30 +0000 Subject: [PATCH] [Sync Iteration] elixir/binary-search/1 --- .../binary-search/1/lib/binary_search.ex | 49 +++++++++++++++++++ 1 file changed, 49 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..b6eaf1e --- /dev/null +++ b/solutions/elixir/binary-search/1/lib/binary_search.ex @@ -0,0 +1,49 @@ +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 + delta = numbers |> tuple_size() |> div(2) + get_index(numbers, key, delta, delta) + end + + defp get_index(numbers, key, index, delta, checked \\ []) + defp get_index(numbers, key, index, _, _) when elem(numbers, index) == key, do: {:ok, index} + defp get_index(_, _, _, 0, _), do: :not_found + + defp get_index(numbers, key, index, delta, checked) when elem(numbers, index) > key do + if index in checked do + :not_found + else + half = div(delta + 1, 2) + get_index(numbers, key, index - half, half, [index | checked]) + end + end + + defp get_index(numbers, key, index, delta, checked) when elem(numbers, index) < key do + if index in checked do + :not_found + else + half = div(delta + 1, 2) + get_index(numbers, key, index + half, half, [index | checked]) + end + end + + defp get_index(_, _, _, _, _), do: :not_found +end