Looking at the following code, write the missing piece of code: public int find(
ID: 3802025 • Letter: L
Question
Looking at the following code, write the missing piece of code: public int find(long searchKey) {int lowerBound = 0; int upperBound = nEleros-1; int curln; while(true) {curln = (lowerBound + upperBound)/2; if(a[curIn]==searchKey) return curln;//found it else if(lowerBound > upperBound) return nElems;//can't find it else//divide range lowerBound = curln + 1;//it's in upper half else upperBound = curln - 1;//it's in lower half}//end else divide range}//end while}//end find()////insert using linear insert - average N stepsExplanation / Answer
After going through the code, it is clear that this is binary search algorithm.
Now coming to the missing part.
Two conditions are already handled,
1) is the middle element itself is search key.
2) if searchkey not found.
So third condition is the split the array, upper half and lower half.
So the condition for that would be
So this condition states that, if the current middle element value is less than search key , then search in the first half else search in lower half.
So here is the final missing code:
else
{
lowerBound = curIn +1;
else
upperBound = curIn -1;
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.