ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

Published at Nov 07 2018
·
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:

```
$ elixir binary_search_test.exs
```

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.

```
if !System.get_env("EXERCISM_TEST_EXAMPLES") do
Code.load_file("binary_search.exs", __DIR__)
end
ExUnit.start()
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
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
```

```
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
do_search(numbers, key, 0, tuple_size(numbers) - 1)
end
defp do_search(_, _, left_index, right_index) when left_index > right_index do
:not_found
end
defp do_search(numbers, key, left_index, right_index) do
middle_index = Integer.floor_div(right_index + left_index, 2)
middle = elem(numbers, middle_index)
cond do
middle == key -> {:ok, middle_index}
middle > key -> do_search(numbers, key, left_index, middle_index - 1)
middle < key -> do_search(numbers, key, middle_index + 1, right_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,450 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments