Given the following method header, give the code for the function using a binary
ID: 3768526 • Letter: G
Question
Given the following method header, give the code for the function using a binary search of an array. Don't worry about the precondition (assume this is already true). public static Boolean has 10 (int[ J 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 10 appears in the array //data[start]...data[end]. A false return value indicates that 10 doesn't appear.Explanation / Answer
public static boolean has10(int[] data,int start,int end)
{
int middle;
middle = (start + end)/2;
if(end<start) //if array segment is empty then 10 is definetely not present
return false;
while( start <= end )
{
if ( data[middle] < 10 )
start = middle + 1;
else if ( data[middle] == 10 )
return true;
else
end = middle - 1;
middle = (start + end)/2;
}
if ( start > end )
return false;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.