I am trying to implement a version of binary search that is a function template. It is to take two iterators that define the range, and the value it is searching for. If the value is found in the range, the function template is to return an iterator to the value. If not found, it is to return the off-the-end iterator. For simplicity, you must be able to do iterator arithmetic with the iterators provided.
This is what I have so far:
template <typename It, typename T> It binary(It beg, It end, T val) {
It mid = beg + (end - beg) / 2;
if (*mid == val)
return mid;
else if (*mid < val)
return mid = binary(mid, end, val);
else if (val < *mid)
return mid = binary(beg, mid, val);
return mid;
}
This function template works fine if the value is found. However, if the value is not found, my program crashes. What happens is that if the value to search for is not found in the range, then the iterator mid gets "stuck" in the sense that it is pointing to either the last element in the container or to the first element in the container. When a recursive call is then made again, mid is recalculated to its exact same position, causing an infinite loop.
I tried to fix it by adding in this piece of code:
template <typename It, typename T> It binary(It beg, It end, T val) {
//New piece of code
if (end - beg == 1 and *beg < val)
return end;
if (end == beg)
//*** WHAT TO RETURN HERE? ***
//old code
It mid = beg + (end - beg) / 2;
if (*mid == val)
return mid;
else if (*mid < val)
return mid = binary(mid, end, val);
else if (val < *mid)
return mid = binary(beg, mid, val);
return mid;
}
This solves the problem if the value to search for is greater than all of the values in the container, but if the the value to search for is less than all of the values in the container, then what do I return? (see my comment in the code that asks "WHAT DO I RETURN HERE?"). I would like to return an iterator that's one past the last element in the original range, but by the time I have reached the condition where beg == end, I have likely already performed many recursive calls to binary, and thus I have no way to access the original end iterator.
I hope all of that makes sense. I'd appreciate any help. Also, I would like to solve this problem whilst still using recursion.