我需要二进制搜索数组的帮助,我的问题是我觉得我有所有正确的要求但它根本没有搜索。我没有收到任何错误消息。只是没有得到我想要的结果。数组是全局初始化的,也是最大字数。 这就是我的功能:
int wordsFindFast(const char const* w){
/*
ROLE Determines whether a given word is in our words array
Implements fast binary search algorithm
PARAMETERS w word to look for in the words array
RETURN VALUE 1 true if the word was found
0 false if the word was not found
*/
int first, middle, last;
first = 0;
last = (MAX_NB_WORDS) - 1;
middle = (first+last)/2;
while(first <= last)
{
if (words[middle] < w){
first = middle + 1;
}//end if
else if(words[middle] == w){
return 1;
}//end else if
else
last = middle - 1;
middle = (first + last)/2;
}//end while
return 0;
}
答案 0 :(得分:1)
你无法比较c中的字符串
if (words[middle] < w)
使用strcmp()
,
while(first <= last)
{
if (strcmp(words[middle],w)==0)
{
return 1;
}
else if(strcmp(words[middle], w)<0)
{
first=middle+1;
}
else
last = middle - 1;
middle = (first + last)/2;
}//end while
答案 1 :(得分:0)
您无法比较C
中的字符串。您应该使用标头strcmp
中声明的标准库函数string.h
逐个字符地比较它们。另外,请注意
const char const *w
函数wordsFindFast
的参数列表中的与
相同const char *w
这意味着w
是指向char
类型的对象的指针,该对象是常量,即是只读的。您应该将功能更改为 -
int wordsFindFast(const char *w) {
int first = 0;
int last = MAX_NB_WORDS;
int middle;
int cmpval;
while(first <= last) {
middle = (first + last) / 2
cmpval = strcmp(w, words[middle]);
if(cmpval == 0)
return 1;
else if(cmpval < 0)
last = middle - 1;
else
first = middle + 1;
}
return 0;
}