Binary Search

The BinarySearch class takes a sorted array of int values in its constructor. The int method .search(int n) looks for the value n in the array by performing a binary search. If the value of n is found, the index is returned. If n is not in the list, a value of -1 is returned.

Although it won't be necessary for the final version of your program, it may be helpful during debugging to print out the values of various instance variables as you look through the array. Feel free to use numerous println() statements to assist you.

Start your debugging with a 5-element array:

int[] a = {2, 4, 6, 7, 9};

Test your search algorithm on it trying to find each of these elements:

2 → Expected result: 0
6 → Expected result: 2
4 → Expected result: 1
8 → Expected result: -1
0 → Expected result: -1
10 → Expected result: -1
9 → Expected result: 4

Then set up a 4-element array and see if it still works:

int[] a = {2, 5, 7, 9};
    

2 → Expected result: 0
5 → Expected result: 1
9 → Expected result: 3
10 → Expected result: -1
4 → Expected result: -1
1 → Expected result: -1

Extension

The Binary Search algorithm can be implemented using loops or recursion. Try implementing the algorithm each way. (The parameters you use for each implementation may be different.) Which of the two implementation strategies do you find easier to work with?