First of all, you can just put
myArr inside
main -- it doesn't need to be a global variable, and your code will still work just fine. (The reason is that you're already passing
myArr as a parameter to the function, so you don't need to make
myArr global.)
Now...
40 41 42
|
int result = binSearch(myArr, 23, answer);
cout << myArr[answer] << " is in position " << result << endl;
|
Since the number you're looking for is
answer, the
cout statement on line 42 should just be
cout << answer << " is in position " << result << endl;
.
Now, for your actual binary search algorithm:
59 60 61 62 63
|
if (mid == searchKey)
return mid;
else if (mid < searchKey)
low = mid + 1;
|
Here, you're comparing the index
mid to the value you're searching for (
searchKey).
What you probably intended to do was compare the element at index
mid with
searchKey:
59 60 61 62 63
|
if (data[mid] == searchKey)
return mid;
else if (data[mid] < searchKey)
low = mid + 1;
|
And on a side note, the code you use to check if the user wants to quit doesn't quite work:
27 28 29 30 31 32 33 34 35 36
|
cout << "Enter search key (or 'x' to exit) : ";
cin >> answer;
char answer2 = (char)answer;
if (answer2 == 'x')
{
cout << "Exiting....." << endl;
quit = true;
}
|
Line 30 will just take the integer value that's stored in
answer (remember,
int
s can't hold anything other than integers, so if you enter a character, it won't "store" it for you in case you wanted to check what the user actually entered) and convert it to a
char
, which will likely be the character whose ASCII value is equal to the number you entered. (For kicks, try entering "120" and see what happens.)
If you want to check whether the user entered a character, you can do something like this:
27 28 29 30 31 32
|
cout << "Enter search key (or 'x' to exit) : ";
if (!(cin >> answer)) // If the input failed, e.g. if you entered a character
{
cout << "Exiting....." << endl;
quit = true;
}
|
Now, this will exit if you enter any non-digit character as the first character.
If you want it to exit only when the user enters "x", that's (slightly) more complicated....
Instead, I would suggest that you make the program exit when the user enters something like -1, which is much easier to check for than a character like "x":
27 28 29 30 31 32 33 34
|
cout << "Enter search key (or -1 to exit) : ";
cin >> answer;
if (answer == -1)
{
cout << "Exiting....." << endl;
quit = true;
}
|
700!