Task

Your task is to implement the method search in the class BinarySearch.

Specification

The method search searches over a given array of ints and returns true, if the value to search for is found.

Implement a binary search. If needed you can add further (private) methods to the class BinarySearch.

Algorithm

To perform a binary search you test the element in the middle of the (sorted) array.

If this is the searched element then the search is terminated as the value is found.

If the middle element in smaller than the value to search then the higher half of the array is used (all element larger than the middle value) and the search is performed again.

This is done until the searched element is either found or the remaining array has only 1 element left.

Support

To support you with implementing the method there are unit tests in BinarySearchTest. The unit tests are disabled at the start. To use them you have to enable them.

Further Challenges

If you solved this exercise already and want a new challenge you can solve this exercise with one of the following constraints:

  • If you implemented the binary search with a recursive algorithm then create an iterative implementation.
  • If you implemented the binary search with an iterative algorithm then create a recursive implementation.
  • Implement the method without using an additional method.
  • To implement a binary search in a generic way (using generics) use the exercise Advanced Binary Search.

Development Requirements

To perform this exercise you need a JDK 8 and Maven 3.3.x.

References