我正在尝试实现二进制搜索来搜索char数组。执行时,程序重复说"字母B在索引1"尽管改变了输入,但永远不会改变。我不确定我哪里出错了。
#include <iostream>
#include <algorithm>
using namespace std;
bool binarySearch(char usedLetters[], int used, char letterToFind);
int main()
{
char a[] = {'A', 'B', 'C'};
int userValue;
cout << "Enter a letter: " << endl;
cin >> userValue;
int result = binarySearch(a, 8, userValue);
if(result == true)
{
cout << "The letter " << a[result] << " was found at the"
" element with index " << result << endl;
}
else
{
cout << "The letter " << userValue << " was not found. " << endl;
}
}
bool binarySearch(char usedLetters[], int used, char letterToFind)
{
int first = 0;
int last = used - 1;
int mid;
int position = -1;
bool found = false;
while (!found && first <= last)
{
mid = (first + last) / 2;
if (usedLetters[mid] == letterToFind)
{
found = true;
position = mid;
}
else if (usedLetters[mid] > letterToFind)
last = mid - 1;
else
first = mid + 1;
}
return position;
}
答案 0 :(得分:0)
您的二进制搜索返回bool
,您返回的是找到该字母的位置,否则为-1。每次找到的位置与0不同时,您的函数将返回1(true),这就是为什么它始终输出它在索引1处找到B的原因。
只需更改二进制搜索即可返回int
并将条件更改为:
if (result == -1)
// Not found
else
// Found