Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement the body of the following function using a binary search of the array.

ID: 3836614 • Letter: I

Question

Implement the body of the following function using a binary search of the array. You do not need to check the precondition. public static boolean has42(int[] data, int start, int end)//Precondition: The elements data[start]...data[end] are sorted from smallest//to largest. This array segment might be empty (indicated by end being less//than start).//Postcondition: A true return value indicates that the number 42 appears in//data[start]...data[end]. A false return value indicates that 42 doesn't//appear.

Explanation / Answer

public static boolean has42(int data[], int start, int end)

   {

       while (start <= end)

       {

           int m = start + (end-start)/2;

           // Check if x is present at mid

           if (data[m] == 42)

               return true;

           // If x greater, ignore left half

           if (data[m] < 42)

               start = m + 1;

           // If x is smaller, ignore right half

           else

               end = m - 1;

       }

       // if we reach here, then element was not present

       return false;

   }