【发布时间】: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