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

The following binary search algorithm will continue searching untile the values

ID: 3864409 • Letter: T

Question

The following binary search algorithm will continue searching untile the values low and high meet, even if by chance the element being targeted is discovered sooner. For example, if we were searching the vector of names for the vlaue "Alex" we would discover the element on the first comparison. Modify the algorithm so that is will halt if the element is discovered.

template<class Iterator, class ValueType>

Iterator lower_bound(Iterator start, Iterator stop, ValueType & value)

{

unsigned int low=0;

unsigned int max = stop - start;

unsigned int high = max;

while(low < high) {

unsigned int mid = (low + high) /2;

if(start[mid] < value)

low = mid +1;

else

high = mid;

}

if (low < max)

return start + low;

return stop;

}

Explanation / Answer

template<class Iterator, class ValueType>
Iterator lower_bound(Iterator start, Iterator stop, ValueType & value)
{
unsigned int low=0;
unsigned int max = stop - start;
unsigned int high = max;
  
while(low < high) {
unsigned int mid = (low + high) /2;
   if (start[mid] == value) return midpoint;
if(start[mid] < value)
low = mid +1;
else
high = mid;
}

if (low < max)
return start + low;
return stop;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote