Question: I am doing a binary search. Here is the code for that. public class SortingAndSearching { public static boolean binarySearch(T[] data, int min, int max,

I am doing a binary search. Here is the code for that.

public class SortingAndSearching { public static > boolean binarySearch(T[] data, int min, int max, T target) { boolean found = false; int midpoint = (min+max) / 2; if(data[midpoint].compareTo(target) == 0) found = true; else if(data[midpoint].compareTo(target) >0) { if (min <= midpoint - 1) found = binarySearch(data, min, midpoint -1, target); } else if(midpoint + 1 <= max) found = binarySearch(data, midpoint + 1, max, target); return found; }

What I need to do is write a main method that searches for 2 different targets in an array (1 should be in the array, 1 should not be.) This is the code I wrote for that.

public static void main(T[] args) { Integer A1[] = {1,2,3,4,5,6}; Integer A2[] = {7,8,9,10,11}; System.out.println("Binary search for 1 is " + binarySearch(A1, 1, 6, 1)); System.out.println("Binary search for 0 is " + binarySearch(A1, 1, 6, 0)); System.out.println("Binary search for 7 is " + binarySearch(A2, 7, 11, 7)); System.out.println("Binary search for 12 is " + binarySearch(A2, 7, 11, 12)); }

It compiles but when I run it the output isn't correct. What am I doing wrong? The first piece of code is copied directly from the book for us to use.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

The code provided has some issues that need to be addressed in order for the binary search to work correctly Lets break it down step by step Step 1 Un... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!