Binary Search for Char Array?

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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;  

	bool found = false; 

	while (first <= last && !found)
	{
		mid = (first + last) / 2; 

		if (usedLetters[mid]== guess)
			found = true;
		else if (usedLetters[mid] > guess)
			last = mid - 1;
		else
			first = mid + 1; 
	}
	if (found)
		return true;
	else
		return false; 
}
Last edited on
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.







Last edited on
Ok! Thankyou.

When I put usedLetters[] in line 1 it gives me a syntax error for the ] and that it expected an expression?
Don't know what you had, so can't tell you why you got an error.

The following compiles for me:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace 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)
			return true;
		if (usedLetters[mid] > guess)
			last = mid - 1;
		else
			first = mid + 1; 
	}
    return false; 
}


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 return true;. Delete your lines 11, 24-26 and remove found from your while loop at line 13.
Last edited on
Topic archived. No new replies allowed.