Published at Mar 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.

For installation and learning resources, refer to the Ruby resources page.

For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:

```
gem install minitest
```

If you would like color output, you can `require 'minitest/pride'`

in
the test file, or note the alternative instruction, below, for running
the test file.

Run the tests from the exercise directory using the following command:

```
ruby binary_search_test.rb
```

To include color from the command line:

```
ruby -r minitest/pride binary_search_test.rb
```

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.

```
require 'minitest/autorun'
require_relative 'binary_search'
class BinarySearchTest < Minitest::Test
def test_it_has_list_data
binary = BinarySearch.new([1, 3, 4, 6, 8, 9, 11])
assert_equal [1, 3, 4, 6, 8, 9, 11], binary.list
end
def test_it_raises_error_for_unsorted_list
skip
assert_raises ArgumentError do
BinarySearch.new([2, 1, 4, 3, 6])
end
end
def test_it_raises_error_for_data_not_in_list
skip
assert_raises RuntimeError do
BinarySearch.new([1, 3, 6]).search_for(2)
end
end
def test_it_finds_position_of_middle_item
skip
binary = BinarySearch.new([1, 3, 4, 6, 8, 9, 11])
assert_equal 3, binary.middle
end
def test_it_finds_position_of_search_data
skip
binary = BinarySearch.new([1, 3, 4, 6, 8, 9, 11])
assert_equal 5, binary.search_for(9)
end
def test_it_finds_position_in_a_larger_list
skip
binary = BinarySearch.new([1, 3, 5, 8, 13, 21, 34, 55, 89, 144])
assert_equal 1, binary.search_for(3)
assert_equal 7, binary.search_for(55)
end
def test_it_finds_correct_position_in_a_list_with_an_even_number_of_elements
skip
binary = BinarySearch.new([1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377])
assert_equal 5, binary.search_for(21)
assert_equal 6, binary.search_for(34)
end
end
```

```
class BinarySearch
attr_reader :list
def initialize(list)
raise ArgumentError.new if list.each_cons(2).any? {|x, y| x > y}
@list = list
end
def middle
list.size / 2
end
def search_for(n)
floor = -1
ceiling = list.size
while floor + 1 < ceiling
mid = (floor + ceiling) / 2
value = list[mid]
if value == n
return mid
elsif value < n
floor = mid
elsif value > n
ceiling = mid
end
end
raise
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,089 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments