I am getting a logic error. It seems simple but its not working
#include <iostream>
using namespace std;
int main(){
int numarray[]={107, 110, 215, 305, 405, 505};
int maxNumElements = 6;
bool elementFound = false;
int inputValue;
int i = 0;
int lowElement = 0;
int highElement = maxNumElements;
cout << "Please enter a value" << endl;
cin >> inputValue;
close! just use 'i' here, don't modify it that is causing it to skip and not see some values. I is modified all you need already.
{
if (inputValue < numarray[i])
{
highElement = i ;
}
The trick with binary search is to be clear on exactly what highElement and lowElement mean. Specifically, is numArray[highElement] a possible match? What about numArray[lowElement]?
I'd arrange them such that numArray[lowElement] <= inputValue < numArray[highElement]. This conforms to the way the standard library works and it's a nice way to think about all intervals. Now let's look at your code with this in mind:
1 2
int lowElement = 0; // okay
int highElement = maxNumElements; // highElement is out of bounds but that's okay.
...
1 2 3 4 5 6 7 8 9 10
if ( inputValue == numarray[i] ) {
elementFound = true;
} else {
if (inputValue < numarray[i]) {
highElement = i - 1; // wrong since numArray[i-1] might be inputValue
// This should be highElement = i;
} else {
lowElement = i + 1; // Okay. We know that numArray[i] != inputValue so may as well set lowElement to the next possible value
}
}
One more note, check your code for the cases when inputValue is smaller than the smallest value in the array, or larger than the largest value.