Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions