2011-04-15 36 views
1

我需要使用二進制搜索來在結構數組中找到請求的名稱。我使用了一個二進制搜索示例代碼,該代碼搜索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小的指數)

+0

是練習在這裏寫你自己的二進制搜索?如果沒有,那麼你可以使用`std :: find`。 – 2011-04-15 14:39:23

+1

你的數組是按contactName排序的嗎? – 2011-04-15 14:43:27

回答

2

如果您嘗試輸入以空格分隔的名稱,則需要使用std::getline而不是istream::operator>>

0

由於您還要求提供一般反饋。請注意,您可能會在每次迭代中將相同的字符串進行兩次比較。 strcmp返回其是否小於,等於或大於(-1,0,1)。你可以得到返回值,並執行所有進一步的比較...

int result = strcmp(entryName, arrayOfStructs[mid].contactName); 
if (result == 0)    
    found = true;   
else   
    if (result < 0)    
    high = mid - 1;   
    else    
    low = mid + 1;