Hi guys, I have a school assignment that requests I'm not being redundant with my binary search algorithm (meaning I don't use a binary search algorithm twice). The problem is I need my function to do two separate things. The first thing it needs to do is find an index value within an array AKA a find() function. This find function returns an index value. The second thing it needs to do, is find a value in between two numbers, so I can insert the number in proper order (between two values). The problem is that I made my function do one but not the other, and I really am not sure how I could could make it do both. Currently, it only can find an index value but it can't find a value in between. This is unusual and perhaps there really isn't a good solution. Any thoughts appreciated.
// Search algorithm
template <class T>
int Set<T>::findIndex(T element){
//int testingArray[9] = { 2, 3, 6, 7, 9, 12, 15, 20, 102 };
//int testingElement = SetSize; // testing value
int iFirst = 0;
int iLast = SetSize;
int iMidElement = iLast / 2;
if (SetSize == 0){
return -1;
}
while (iFirst <= iLast){
iMidElement = (iFirst + iLast) / 2;
}
if (ElementArray[iMidElement] > element){
iLast = iMidElement - 1;
}
if (ElementArray[iMidElement] < element){
iFirst = iMidElement + 1;
}
if (ElementArray[iMidElement] == element){
return iMidElement;
}
}
return -1;
}
// Function I want to use the algorithm with
template <class T>
void Set<T>::insert(T nextElement){
int i = findIndex(nextElement);
if (i != -1){
return;
}
try{
if (SetCapacity == 0){
this->ElementArray = this->reallocate(1);
}
elseif (SetSize == SetCapacity){
this->ElementArray = this->reallocate(SetCapacity * 2);
}
}
catch (bad_alloc){
cerr << "ERROR: Unable to allocate a new buffer for Vector\n";
}
///////////////////////////////////////////////////////////////
// THIS IS WHERE THE FUNCTION SHOULD BE CALLED, BUT I'M NOT SURE HOW
///////////////////////////////////////////////////////////////
SetSize++;
return;
}
// Find function. This part is already complete.
template <class T>
SetIterator<T> Set<T>::find(T element){
int i = findIndex(element);
if (i >= 0){
return ElementArray + i;
}
else{
return end();
}
}