From ecdcae71419f8be2d1d311fb7b5875f8f7c87903 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 13:50:45 +0000 Subject: [PATCH] [Sync Iteration] elixir/binary-search/2 --- .../binary-search/2/lib/binary_search.ex | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 solutions/elixir/binary-search/2/lib/binary_search.ex diff --git a/solutions/elixir/binary-search/2/lib/binary_search.ex b/solutions/elixir/binary-search/2/lib/binary_search.ex new file mode 100644 index 0000000..aa82129 --- /dev/null +++ b/solutions/elixir/binary-search/2/lib/binary_search.ex @@ -0,0 +1,33 @@ +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({}, _), do: :not_found + def search(numbers, key), do: get_index(numbers, key, tuple_size(numbers) - 1) + + defp get_index(numbers, key, min \\ 0, max) do + case min + div(max - min, 2) do + index when elem(numbers, index) == key -> {:ok, index} + index when elem(numbers, index) > key and index < max -> get_index(numbers, key, min, index) + index when elem(numbers, index) < key and index > min -> get_index(numbers, key, index, max) + _ when elem(numbers, max) == key -> {:ok, max} + _ -> :not_found + end + end +end