c ++二进制搜索返回(找到)无论用户类型

时间:2016-07-24 19:19:05

标签: c++ binary-search bubble-sort

我正在制作一个刽子手游戏,我正在试图弄清楚为什么无论用户输入什么类型它返回"该字母已被使用\ n&#34 ;;

这是功能定义......

bool binarySearch(char usedLetters[], int used, char letterToFind)
{

    bool found = false;
    int mid = 0, first = 0, last = used - 1;
    while (!found && first <= last)
    {
        mid = (first + last) / 2;
        if (usedLetters[mid] == letterToFind)
            found = true;
        else if (usedLetters[mid] > letterToFind)   // works on ascending sorted collections only
            last = mid - 1;             // first half   
        else
            first = mid + 1;            // last half
    }
    if (found)
        return mid;
    return -1;
}

这是声明......

char gLetter;
int wrong = 0;
int gameStatus = 5;
int chances = 0;
int used = 0;
int letterIndex;

这是main ...中的函数调用。

while (wrong != 6)                          // Function to find out which hangman board to print to user
{
    cout << "<<<<<<<<<< MAKE A GUESS >>>>>>>>>>\n";
    cout << "Guessed Letters: " << usedLetters << endl;
    cout << "\nEnter a letter to guess: ";
    cin >> gLetter;
    gLetter = toupper(gLetter);

    usedLetters[used++] = gLetter;

    letterIndex = binarySearch(usedLetters, used, gLetter);     // Binary search for letters used

    bubbleSort(usedLetters, used);

    if (letterIndex == -1)
    {
        continue;
    }

    else
    {
        cout << "That letter has already been used\n";
    }

只需要弄清楚为什么用户输入的字符在它们尚未被使用时总是被找到。我认为这是因为我声明&#34; int used = 0&#34;但是当我把它改成别的东西时,比如26,二进制搜索不会返回任何字母。

1 个答案:

答案 0 :(得分:4)

false为0.其他任何内容都是true

bool binarySearch(char usedLetters[], int used, char letterToFind)
...
    if (found)
        return mid;
    return -1;

如果您在索引零处找到某些内容(false为0),则只返回mid

另见http://ideone.com/2XU2bn

- 编辑 -

你表示你只想知道这封信是否存在,所以只需返回found