Binary Search Issues

Hello! So below, I have a piece of code that is part of a hangman game. What I am doing is asking for a guess, storing each guess in an array, and then trying to check and see whether the user has already guessed the letter or not. I'm not sure if I'm just not implementing the binary search algorithm right or if it has to do with the way I'm handling the bool aspect of the binarySearch function. There's something wrong in that regard, can you help me? I'm generally a little confused.

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include<iostream>

using namespace std; 

bool binarySearch(char usedLetters[], int numGuessedLetters, char guess);
void bubbleSort(char usedLetters[27], int used);
int main()
{
	char guess; 
	char usedLetters[26];
	int  numGuessedLetters = 0;
	int i = 0;

	do{
		cout << "Please guess a letter." << endl;
		cin >> guess;

		//Putting each guess into an array and remembering how many letters have been guessed
		usedLetters[numGuessedLetters++] = guess;

		//Using bubblesort function to alphebatize the list of the users guessed letters
		bubbleSort(usedLetters, numGuessedLetters);

		//Searches to see if user has already guessed that letter or not
		binarySearch(usedLetters, numGuessedLetters, guess);

		if (true)

			cout << "Been guessed!" << endl;

		else
			cout << "Letter has not been guessed!" << endl;
		i++;
	} while (i < 5); 
	cout << "\n\n";
	system("pause"); 
	return 0; 
}

bool binarySearch(char usedLetters[], int numGuessedLetters, char guess)
{
	int low = 0;
	int high = numGuessedLetters - 1;

	int mid;

	while (low <= high)
	{
		mid = (low + high) / 2;

		if (guess == usedLetters[mid])
		{
			return true;
		}
		else if (guess > usedLetters[mid])
		{
			low = mid + 1;
		}
		else
		{
			high = mid - 1;
		}
	}

	return -1;
}

void bubbleSort(char usedLetters[27], int numGuessedLetters)
{
	for (int x = 0; x < numGuessedLetters; x++)

		for (int x = 0; x < numGuessedLetters; x++)

		{
	
			for (int i = 0; i<numGuessedLetters - 1; i++)

			{

				if (usedLetters[i]>usedLetters[i + 1])

				{

					int temp = usedLetters[i + 1];

					usedLetters[i + 1] = usedLetters[i];

					usedLetters[i] = temp;

				}

			}

		}

}
Last edited on
Topic archived. No new replies allowed.