2013-01-07 159 views
0

字符串數組我想要寫在C二進制搜索用C

一個字符串數組我寫了這個代碼,二進制搜索,並沒有錯誤編譯,但是當我試圖尋找它沒有給出結果。任何幫助,將不勝感激。

字符串是一個類型def。對不起,沒有在開始時澄清這一點。

//Looks up word s, in dictionary. 
bool lookup(string s) 
{ 
    int min = 0; 
    int max = dictionary.size - 1; 
    int mid; 
    bool found = false; 

    while (min <= max && !found) 
    { 
     mid = (min + max) /2; 
     if (dictionary.words[mid].letters == s) 
      found = true; 
     else if (dictionary.words[mid].letters > s) 
      max = mid -1; 
     else 
      min = mid + 1; 
    } 
    return found; 
} 
+2

這個'C'如何? 'string'是一個typedeff的結構,還是這個'C++'? –

+1

你使用C還是C++?你不能在C中使用'std :: string',如果你使用cstrings('char'數組),你不能用==來比較它們(或者至少不是你的方式認爲)。 – sonicwave

+0

該算法看起來是正確的。如果您需要幫助,請將我們指向代碼。 – Flash

回答

1

字符串在C是剛字符數組,並且因爲使用==陣列之間的比較只比較起始地址,您需要使用librray功能strcmpstring.h比較數組的內容。像這樣:

if (strcmp(dictionary.words[mid].letters, s) == 0) 

編輯

我看到,儘管c標籤,你有某種string型。這是C還是C++?

0

我認爲這將有助於粘貼字符串和字典結構。

假設字典是單詞的排序數組。字符串(字符數組)和字符串是一個字符數組以及那麼我會假設,當你做dictionary.words[int].letters 返回類型是一個內存和相同的是與s的情況。由於兩個字符串保存在不同的內存位置,因此無法找到該字符串。

嘗試通過遍歷字符串比較字符串

bool lookup(string s) 
{ 
    int min = 0; 
    int max = dictionary.size - 1; 
    int mid; 
    bool found = false; 
    int i; 
    int length = 0;     //calculate the length of the input string 
    while (s[length] != '\0') 
    { 
    length++; 
    } 

    while (min <= max && !found) 
    { 
     mid = (min + max) /2; 
     for(i=0;i<length;i++) 
     { 
      if(dictionary.words[mid].letters[i] == '\0') 
       break; 
      if (dictionary.words[mid].letters[i] == s[i]) 
       continue; 
      else if (dictionary.words[mid].letters[i] > s[i]) 
       max = mid -1; 
      else 
       min = mid + 1; 
      break; 
     } 
     if(i==length) 
      found=true; 
    } 
    return found; 
} 

我還沒有編譯的代碼,但是這應該給你的要點。