帮助实现二进制搜索结构数组中的名称
||
我需要使用二进制搜索在结构数组中查找请求的名称。我使用了一个二进制搜索示例代码,该代码搜索ints并对其进行了修改,以搜索数组索引以比较每个结构中的名称。该程序可以运行,但是从未找到该名称,因此肯定某个地方出了问题。不知道这是我从流中获取名称的方式,还是只是我一般的搜索实现方式。谁能看看提供一些反馈?谢谢
输入函数的相关代码:
char entryName[31];
char discard;
string entryNameString;
cout << \"What is the name of the entry you would like to look up?\" << endl;
cin >> entryNameString;
cin.get(entryName, 30);
cin.get(discard);
findName(listLength, arrayOfStructs, entryName);
二进制搜索功能:
void findName(int listLength, contactInfo* arrayOfStructs, const char* entryName)
{
bool found = false;
int low = 0, high = listLength-1, mid;
while (!found && low <= high)
{
mid = (low + high) / 2;
if (strcmp(entryName, arrayOfStructs[mid].contactName) == 0)
found = true;
else
if (strcmp(entryName, arrayOfStructs[mid].contactName) < 0)
high = mid - 1;
else
low = mid + 1;
}
if (found)
{
cout << arrayOfStructs[mid].contactName << endl;
cout << arrayOfStructs[mid].birthday << endl;
cout << arrayOfStructs[mid].addressInfo.streetName << endl;
cout << arrayOfStructs[mid].addressInfo.cityName << endl;
cout << arrayOfStructs[mid].addressInfo.state << \" \";
cout << arrayOfStructs[mid].addressInfo.zipcode << \" \";
cout << arrayOfStructs[mid].addressInfo.phoneNumber << endl;
cout << arrayOfStructs[mid].typeOfentry << endl;
}
else
cout << \"NOT FOUND\" << endl;
}
编辑:arrayOfstructs []。contactName按字母顺序排序(例如.contactName = Amanda,位于比.contactName = Zorak小的索引中)
没有找到相关结果
已邀请:
2 个回复
递劝臼类洪
而不是
。
芳菱挨啡