Published at Aug 14 2019
·
0 comments

Instructions

Test suite

Solution

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.

Execute the tests with:

```
$ mix test
```

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!"
end
```

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

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

```
defmodule BinarySearchTest do
use ExUnit.Case
test "returns :not_found on empty tuple" do
assert BinarySearch.search({}, 2) == :not_found
end
@tag :pending
test "returns :not_found when key is not in the tuple" do
assert BinarySearch.search({2, 4, 6}, 3) == :not_found
end
@tag :pending
test "returns :not_found when key is too high" do
assert BinarySearch.search({2, 4, 6}, 9) == :not_found
end
@tag :pending
test "finds key in a tuple with a single item" do
assert BinarySearch.search({3}, 3) == {:ok, 0}
end
@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}
end
@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}
end
@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}
end
@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}
end
end
```

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

```
defmodule BinarySearch do
# NOTE: By the time this guard has been reached, search options will have
# been exhausted, and the `left` index will have been incremented, or the
# `right` index decremented, to a number where we would be attempting to
# perform an out-of-bounds search on position `left` of a "sub-tuple" of
# length `right`.
defguardp key_not_found?(left, right) when left > right
@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({}, _key), do: :not_found
def search(numbers, key) do
search(numbers, key, 0, tuple_size(numbers) - 1)
end
defp search(_numbers, _key, left, right) when key_not_found?(left, right) do
:not_found
end
defp search(numbers, key, left, right) do
middle_index = div(left + right, 2)
middle_element = elem(numbers, middle_index)
cond do
middle_element > key ->
search(numbers, key, left, middle_index - 1)
middle_element < key ->
search(numbers, key, middle_index + 1, right)
true ->
{:ok, middle_index}
end
end
end
```

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?

Level up your programming skills with 3,081 exercises across 51 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments