Hello, I definitely know how to implement binary search when it comes to integers but I need to do it with a char array for a class project. I'm not good with using bool functions so I'm not sure if this thing will even work for me. It just needs to tell me whether or not I've used the letter before! in line 1 I'm not sure what to do as I'm getting a syntax error. The logic, I'm not sure about.
line 1: usedLetters is a single char. You probably meant usedLetters[].
line 17,19: You're treating length as an array (trying to subscript it), while it is declared as a simple int at line 4. Did you mean usedLetters[mid]?
line 25,27: You're trying to return int values, but your function is declared as bool.
#include <iostream>
usingnamespace std;
bool binarySearch (char usedLetters[], int numGuessedLetters, char guess)
{
int length = sizeof(usedLetters) / sizeof(usedLetters[0]);
cout << length << endl;
int first = 0;
int last = length - 1;
int mid;
while (first <= last)
{ mid = (first + last) / 2;
if (usedLetters[mid]== guess)
returntrue;
if (usedLetters[mid] > guess)
last = mid - 1;
else
first = mid + 1;
}
returnfalse;
}
Note that the calculation of length (your line 4) is not going to work the way you're thinking. Since usedLetters is declared with [], the compiler does not know how large the array is.
edit: You can also clean up the code somewhat. You don't need found at all. Your line 18, simply returntrue;. Delete your lines 11, 24-26 and remove found from your while loop at line 13.