搜索不工作需要一些建议

问题描述:

处理二分查找。下面的代码应该解释我正在尝试做什么。用户输入一个单词,然后执行二进制搜索以搜索单词列表。问题是二分查找。它正在运行,但它没有找到单词表中的单词,即使我知道它在那里。我知道代码可能会更好,但它应该工作。任何人都可以放光搜索不工作需要一些建议

#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

您的二进制文件搜索功能被忽略了在传递的值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