The BinarySearchDemo program has a static method
binSearch that takes two parameters: an array of sorted
int values, and an integer to look for in that array. The
method uses a binary search to look through the values in the array. If
the search value is found, the index of that value is returned.
Otherwise, a value of -1 is returned.
A static main method initializes a few arrays--see below
for examples--and calls binSearch with test values to
ensure that it works.
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
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?