处理二进制搜索。下面的代码应该解释我正在尝试做什么。用户输入一个单词,然后实现二进制搜索以搜索单词表。问题是二进制搜索。它正在运行,但即使我知道它在那里,它也没有在wordlist中找到这个词。我知道代码可能更好但它应该工作。有人放光了吗?
#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 :(得分:1)
您的二进制搜索功能忽略了传入的值left
和right
。
不应该。
它可能应该开始:
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;