Exercism v3 launches on Sept 1st 2021. Learn more! ๐Ÿš€๐Ÿš€๐Ÿš€
Avatar of thekeele

thekeele's solution

to Binary Search in the Elixir Track

Published at May 31 2019 · 0 comments
Test suite


This exercise has changed since this solution was written.

Implement a binary search algorithm.

Searching a sorted collection is a common task. A dictionary is a sorted list of word definitions. Given a word, one can find its definition. A telephone book is a sorted list of people's names, addresses, and telephone numbers. Knowing someone's name allows one to quickly find their telephone number and address.

If the list to be searched contains more than a few items (a dozen, say) a binary search will require far fewer comparisons than a linear search, but it imposes the requirement that the list be sorted.

In computer science, a binary search or half-interval search algorithm finds the position of a specified input value (the search "key") within an array sorted by key value.

In each step, the algorithm compares the search key value with the key value of the middle element of the array.

If the keys match, then a matching element has been found and its index, or position, is returned.

Otherwise, if the search key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right.

If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not found" indication is returned.

A binary search halves the number of items to check with each iteration, so locating an item (or determining its absence) takes logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.

Running tests

Execute the tests with:

$ elixir binary_search_test.exs

Pending tests

In the test suites, all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by commenting out the relevant @tag :pending with a # symbol.

For example:

# @tag :pending
test "shouting" do
  assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"

Or, you can enable all the tests by commenting out the ExUnit.configure line in the test suite.

# ExUnit.configure exclude: :pending, trace: true

If you're stuck on something, it may help to look at some of the available resources out there where answers might be found.


Wikipedia http://en.wikipedia.org/wiki/Binary_search_algorithm

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.


if !System.get_env("EXERCISM_TEST_EXAMPLES") do
  Code.load_file("binary_search.exs", __DIR__)

ExUnit.configure(exclude: :pending, trace: true)

defmodule BinarySearchTest do
  use ExUnit.Case

  test "returns :not_found on empty tuple" do
    assert BinarySearch.search({}, 2) == :not_found

  @tag :pending
  test "returns :not_found when key is not in the tuple" do
    assert BinarySearch.search({2, 4, 6}, 3) == :not_found

  @tag :pending
  test "returns :not_found when key is too high" do
    assert BinarySearch.search({2, 4, 6}, 9) == :not_found

  @tag :pending
  test "finds key in a tuple with a single item" do
    assert BinarySearch.search({3}, 3) == {:ok, 0}

  @tag :pending
  test "finds key when it is the first element in tuple" do
    assert BinarySearch.search({1, 2, 4, 5, 6}, 1) == {:ok, 0}

  @tag :pending
  test "finds key when it is in the middle of the tuple" do
    assert BinarySearch.search({1, 2, 4, 5, 6}, 4) == {:ok, 2}

  @tag :pending
  test "finds key when it is the last element in tuple" do
    assert BinarySearch.search({1, 2, 4, 5, 6}, 6) == {:ok, 4}

  @tag :pending
  test "finds key in a tuple with an even number of elements" do
    tuple = {1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377}
    assert BinarySearch.search(tuple, 21) == {:ok, 5}
    assert BinarySearch.search(tuple, 34) == {:ok, 6}
defmodule BinarySearch do

  @spec search(tuple, integer) :: {:ok, integer} | :not_found
  def search({}, _), do: :not_found
  def search(numbers, key) do
    numbers = Tuple.to_list(numbers)

    binary_search(numbers, key, 0, length(numbers))

  defp binary_search(_, _, low, high) when low > high, do: :not_found
  defp binary_search(numbers, key, low, high) do
    middle = floor((low + high) / 2)
    current = Enum.at(numbers, middle)

    cond do
      current < key -> binary_search(numbers, key, middle + 1, high)
      current > key -> binary_search(numbers, key, low, middle - 1)
      true -> {:ok, middle}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other peopleโ€™s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?