我需要使用二進制搜索來在結構數組中找到請求的名稱。我使用了一個二進制搜索示例代碼,該代碼搜索ints並對其進行修改以搜索數組indecies,以比較每個結構中的名稱。該程序運行,但名稱從來沒有找到,所以某些地方肯定會出錯。不知道這是我從流中獲取名稱的方式,還是僅僅通過我一般的搜索實現。任何人都可以看看提供一些反饋?來自輸入功能感謝幫助在結構數組中執行二進制搜索
培訓相關的代碼:
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 =阿曼達,位於比.contactName = Zorak小的指數)
是練習在這裏寫你自己的二進制搜索?如果沒有,那麼你可以使用`std :: find`。 – 2011-04-15 14:39:23
你的數組是按contactName排序的嗎? – 2011-04-15 14:43:27