2011-12-23 38 views
0

處理二分查找。下面的代碼應該解釋我正在嘗試做什麼。用戶輸入一個單詞,然後執行二進制搜索以搜索單詞列表。問題是二分查找。它正在運行,但它沒有找到單詞表中的單詞,即使我知道它在那裏。我知道代碼可能會更好,但它應該工作。任何人都可以放光搜索不工作需要一些建議

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 


char dictionary[400000][45]; 

int main(void) 
{ 
FILE infile; 
int i=0; 
int num; 
int index; 
char buffer[45]; 
char userword[45]; 

fp1 = fopen("C:/Users/Aaron/ProgrammingAssignment/dictionary.txt","rb"); 

    if (fp1 == NULL) 
    { 
    printf("The dictionary file did not open\n"); 
    exit(0); 
    } 

    else 
    { 
    printf("Dictionary file is open\n"); 
    } 

    while(fgets(buffer,45, fp1)!=NULL) 
     { 
      strcpy(wordlist[i],buffer); 
      //printf("Line %d: %s",i,wordlist[i]); 
      i++; 
     } 

    printf("Your wordlist is now in the dictionary array"); 

    do 
    { 
    //fscanf(fp2,"%s", userword); 
    printf("Enter a word to be spell checked: "); 
    fgets(userword, 43, stdin); 

    //and do a binary search 
    index = BinarySearch(userword,0,i); 
    if(index > -1) 
     printf("%s was found in the wordlist", userword); 
    else 
     printf("%s was not found in the dictionary", wordcheck); 
    } 
    while(wordlist != NULL); 

    if(index>-1) //The word was found 
    { 
     printf("That is correctly spelled\n"); 
    } 
    else 
    { 
     printf("That word is spelt wrong\n"); 
    } 


return 0; 
} 

int BinarySearch(const char userword[],int left,int right) 
    { int high = 400000; 
    int low = 0; 
    int target; 
    int count = 0; 

    while (high >= low) 
     { target = low + ((high - low)/2); 

     // show tries for demonstration only 
     printf("%d, ",target); 

     if (strcmp(userword, wordlist[target]) < 0) 
      high = target -1; 
     else if (strcmp(userword, wordlist[target]) > 0) 
      low = target + 1; 
     else 
     return target; 
     } 
    return -1; 
    } 
+0

我把'dictionary.txt'中的初始輸入命令是? – fge 2011-12-23 23:12:39

+0

是的,它已經訂購了文字 – adohertyd 2011-12-23 23:15:52

回答

1

您的二進制文件搜索功能被忽略了在傳遞的值leftright

它不應該。

它也許應該開始:

int BinarySearch(const char userword[], int left, int right) 
{ 
    int high = right; 
    int low = left; 

你應該關閉的字典你讀完之後。

您需要考慮right是否是最後一個有效元素的索引或'最後一個元素的索引之後的索引'。這可能意味着您需要將i - 1傳遞給函數。

您應該考慮調用strcmp()一次並獲取其返回值;它是比較昂貴的:

int rc = strcmp(userword, wordlist[target]); 

if (rc == 0) 
    return target; 
else if (rc < 0) 
    high = target - 1; 
else 
    low = target - 1; 
+0

右邊應該是最後一個有效元素的索引。我真的不確定使用二進制搜索,你能解釋一下嗎? – adohertyd 2011-12-23 23:25:32

+0

主程序中的'i'是數組中第一個無效元素的索引,所以'main()'中的調用可能應該是'index = BinarySearch(userword,0,i-1);'。另一個可能的問題可能是循環終止條件:'while(高> =低)'。我沒有坐下來研究你的代碼是否正確。但我知道(從閱讀喬恩本特利的「編程珍珠」和「更多編程珍珠」),二進制搜索是非常棘手的100%正確。你應該在查全文字典之前測試大小爲0,1,2,3,4字的'字典'。 – 2011-12-23 23:43:36