Question: During a binary search, which entries in the array: a[] = [ 4, 8, 12, 14, 20, 24 ] are compared to the target when

During a binary search, which entries in the array:

a[] = [ 4, 8, 12, 14, 20, 24 ]

are compared to the target when the target is  a) 2;  b) 8;  c) 15.


  • Use the textBox for your answer.


Question:


Modify the method inArray() below(note error correction below) so that it returns the index of the first array entry that equals anEntry.  If the array does not contain such an entry, return -1.  You will have to modify binarySearch() also.

  • Use the array  a[] = [ 4, 8, 12, 14, 20, 24 ]
  • Search for  a) 2 (index = -1);  b) 8 (index = 1);  c)  15 (index = -1)
  • Write aa main() to do Question#7.
  • Use the method inArray() below.  Note the correction in the parameter list:
         inArray( T[] anArray, T anEntry )
  • Use the method binarySearch().

private static >

boolean binarySearch(T[] anArray, int first, int last, T desiredItem)

{

boolean found = false;

int mid = first + (last - first) / 2;

if (first > last)

found = false;

else if (desiredItem.equals(anArray[mid]))

found = true;

else if (desiredItem.compareTo(anArray[mid]) < 0)

found = binarySearch(anArray, first, mid - 1, desiredItem);

else

found = binarySearch(anArray, mid + 1, last, desiredItem);

return found;

}

 

Now the public method inArray appears as follows: 

public static > boolean inArray(T anEntry)

 { 

return binarySearch(anArray, 0, anArray.length − 1, anEntry); 

} // end inArray

Step by Step Solution

3.31 Rating (154 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

Step 1 Lets start by modifying the inArray method as per the given instructions Heres the corrected ... 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 Programming Questions!