使用C

时间:2018-04-02 12:27:26

标签: c binary-search bsearch

所以我试图在C中使用bsearch函数在字符串数组中进行二进制搜索。由于某种原因,它总是返回NULL。对于bsearch的比较功能,我没有使用strcmp,我自己做了,令人惊讶的是,它适用于我手动实现二进制搜索功能。我会解释一下,无论如何,这是我的主要代码:

int main(){

  int n;
  scanf("%d", &n);
  if(n<=0) qerror();

  char ** words = (char **)calloc(n, sizeof(char *));
  if(words == NULL) qerror();
  int i = 0;
  for(;i<n;i++){

    words[i] = (char *)calloc(MAX, sizeof(char));
    if(words[i] == NULL) qerror();
    scanf("%s", words[i]);

  }

  char seek_word[MAX];
  scanf("%s", seek_word);
  char ** c = (char **)bsearch(seek_word, words, n, sizeof(char *), &b_compare_words);

  if(c == NULL) printf("-1\n");
  else printf("%d\n", c - words);


  //printf("%d\n", bin_search_string(words, n, seek_word)); //manuelna binarna pretraga
  free(words);

  return 0;
}

此代码的第一部分只是创建一个字符串数组(命名字),其中包含长度为MAX的N个字符串(这是在开头定义的宏)。我已经测试过这个部分并且它有效,所以这不是问题。

之后,输入seek_word,这就是我们试图在'words'中找到的单词。我称之为bsearch,作为比较函数,我使用了自己创建的函数。这是它的样子:

int compare_words(char * a, char * b){
  int i = 0;
  while(a[i] && b[i]){

    char ac = tolower(a[i]), bc = tolower(b[i]);
    if(ac < bc) return -1;
    else if (ac > bc) return 1;
    i++;

  }
  return 0;
}

int b_compare_words(const void * a, const void * b){
  return compare_words((char *)a, (char *)b);
}

实际比较工作是在compare_words函数中完成的,我在b_compare_words函数中调用了该函数,我只是将void指针转换为char指针。 无论我对此进行测试,我得到-1(意味着bsearch返回的指针为NULL)。 现在这是有趣的部分。除此之外,我已经创建了自己的二元搜索功能,它可以完成同样的工作并且可以工作(你可以看到我在下面评论过的部分)。该函数称为bin_search_string,它看起来像这样:

int bin_search_string(char ** a, int n, char * x){

    int l_index = 0;
    int r_index = n-1;
    int check_index;
    while(l_index <= r_index){
      check_index = l_index + (r_index - l_index)/2;
      int test = compare_words(x, a[check_index]);
      if(test == 0) return check_index;
      else if(test < 0) l_index = check_index + 1;
      else r_index = check_index - 1;

    }
    return -1;

}

如您所见,此函数使用我也传递给bsearch的相同compare_words函数。但是当我使用自己的函数测试我的程序时,它确实有效(返回找到字符串的索引)。 那么,为什么bsearch不起作用的任何想法? 提前谢谢。

0 个答案:

没有答案
相关问题