【问题标题】:Trying to recursively binary search strings in c尝试在c中递归二进制搜索字符串
【发布时间】:2014-08-10 13:45:49
【问题描述】:

我需要使用二分查找递归查找目标字符串。如果未找到该函数应返回 -1,如果找到则返回正整数,但始终返回 -1。感谢您的帮助!

int start = 0;
int search;
search = binary_search(strings, target, start, size-1);
if(search == -1)
{
printf("Not in the dataset!");
}
if(search != -1)
{
printf("%s is in the dataset", target);
}

int binary_search(char **strings, char *target, int start_idx, int end_idx)
{
if(end_idx < start_idx)
    {
    return -1;
    }
int middle = ((start_idx + end_idx)/2);
int i;
i = strcmp(target, strings[middle]); 
if(i == 0)
    {
    return middle;
    }
if(i < 0)
    {
    return binary_search(strings, target, start_idx, middle-1);
    }
else
    {
    return binary_search(strings, target, middle+1, end_idx);
    }
}    

输入数据: 亚丁 卡登 大卫 埃里克 约翰 标记 马特 麦卡 菲尔 苏珊

【问题讨论】:

  • 请展示一个完整的例子,包括输入数据和函数调用。见sscce.org
  • 仅供参考,您不需要指针基础、开始和结束。您可以使用基于指针、长度和一些指针数学来做到这一点。它实际上让我更容易掌握(无论如何对我来说)。
  • 我不确定你想做什么,比较字符串中的字符串?或比较字符串数组?
  • 另外,strings 数组是否已排序?
  • 有什么问题?代码不起作用吗?输入、输出和预期输出是什么?请在how to ask a question 上查看本指南。

标签: c string recursion binary-search


【解决方案1】:

尽管众所周知,二分搜索很难正确,但我没有看到您的算法中有任何错误,如图所示。由于无法根据提供的信息确定的各种原因,您仍然可能失败(-1)。

1) 您的源字符串列表实际上没有正确排序 - strcmp() 使用 ASCII 比较,而不是字典比较,即您的源字符串必须是 ASCII 排序才能使 bsearch 有效。

2) 您的源字符串不是格式良好的以 NUL 结尾的 C 字符串。

3) 目标字符串在源字符串列表中没有完全匹配。即,搜索“bill”不会匹配“Bill”或“billiard”

请注意,递归 bsearch 比非递归解决方案更慢并且使用更多内存

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-17
    • 2020-09-27
    • 2021-04-28
    • 2022-08-02
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多