【发布时间】:2016-08-12 07:03:28
【问题描述】:
在这段代码中:
- 我读取了文件
~/usr/share/dict/word的内容并将它们存储在数组中。 - 然后开始对该数组进行二分搜索算法,但问题是在将数组传递给第 62 行的二分搜索函数并尝试将其与
binary_search(string* dictionary, string key)方法中的键进行比较之后。 - 我发现它出于某种我不知道的原因将
key与这个未知字符串"��tudes"进行比较。 - 我确信该数组包含正确的数据。
代码:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#define MAX 99171
// Prototype //
int binary_search(string*, string);
int main(int argc, string argv[])
{
// Attributes //
string dictionary[MAX];
FILE* dictionaryFile = fopen("words", "r");
char output[256];
string key = argv[1];
// Check if their is a problem while reading the file //
if (dictionaryFile == NULL)
{
// If everything got fouled up then close the file //
fclose(dictionaryFile);
printf("couldn't read the file!!!\n");
return 1;
}
// storing the information into an array to make it easy to read //
for(int i = 0; i < MAX; i++)
{
fgets(output, sizeof(output), dictionaryFile);
dictionary[i] = output;
}
// Binary Search a word //
if(binary_search(dictionary, key) == 1)
{
printf("word was found !!!\n");
}
else if(binary_search == 0)
{
printf("word was not found !!!\n");
}
// If Everything goes just fine close the file //
fclose(dictionaryFile);
return 0;
}
// implementing prototype //
/**
@arag dictionary
a string of english words
@arg key
a key we looking for
@return
0 if didn't find the key and 1 otherwise
*/
int binary_search(string* dictionary, string key)
{
// pointer to the start and the end of the array //
int start = 0;
int end = MAX - 1;
int mid;
// while end is greater than the start //
while (end > start)
{
// Get The Middle Element //
mid = (start + end) / 2;
printf("%s\n", dictionary[mid]);
// Check if the middle elemenet //
if (strcmp(key, dictionary[mid]) == 0)
{
return 1;
}
// Check the left half //
else if(strcmp(key, dictionary[mid]) < 0)
{
end = mid - 1;
}
// Check the right half //
else if (strcmp(key, dictionary[mid]) > 0)
{
start = mid + 1;
}
}
// didn't find the key //
return 0;
}
注意:cs50.h 库是由哈佛制作的,作为像我这样的初学者的训练轮,我在我的代码中使用它,这是指向其 reference 的链接。
【问题讨论】:
-
什么是“字符串”?这甚至可以编译吗?
-
用于字典实现.. 最好使用 trie 数据结构。
-
@Sigstop:正如 OP 已经明确表示的那样,这是一个示例程序。数组的二进制搜索在这里很好。尝试将是矫枉过正。
-
dictionary只是一个指针数组,并且该数组中的每个指针都指向完全相同的位置:output。您需要复制每个字符串。此外,您需要 remove the newline 将fgets留在缓冲区中。 -
@LeeDanielCrocker 正如我在注释中所说,我使用了一个 cs50 库,它具有这个字符串数据类型 AKA char *
标签: c arrays string binary-search cs50