【发布时间】:2017-10-17 19:56:20
【问题描述】:
我正在尝试创建一个二分搜索算法,并使用了两组 if 语句来判断样本是偶数/不偶数的情况。不均匀的一面当前按计划工作并返回true,均匀的一面返回true,但随后进入函数底部的“catch all”代码段并返回false:
bool search(int value, int values[], int n)
{
//searching algorithm
if (n <= 0)
{
return false;
}
//searching algorithm where n is even, if b is not the searched for value, split the sample and run recursively until value is equal to b or n<=0
if (n % 2 == 0)
{
int starte = n / 2;
eprintf("starte is %i", starte);
int startpluse = starte + 1;
int b = values[starte];
eprintf("b is %i", b);
//for (int i=0; i<n; i++){
//printf("%i,",values[i]);}
if (b == value)
{
printf("true\n");
return true;
}
else
{
if (value > b)
{
int o = starte - 1;
int searcharrayc[o];
for (int h = startpluse, l = 0; l < o; h++, l++)
{
searcharrayc[l] = values[h];
}
search(value, searcharrayc, o);
}
if (value < b)
{
int searcharrayd[starte];
for (int m = 0; m < starte; m++)
{
searcharrayd[m] = values[m];
}
search(value, searcharrayd, starte);
}
}
}
//searching algorithm where n is uneven, if a is not the searched for value, split the sample and run recursively until a is equal to the value or n<=0
if (n % 2 == 1)
{
eprintf("n is %i", n);
int start = (n / 2) - 0.5;
int startplus = start + 1;
int a = values[start];
eprintf("a is %i", a);
if (a == value)
{
return true;
}
else
{
if (value > a)
{
int searcharray[start];
for (int i = startplus, j = 0; j < start; i++, j++)
{
searcharray[j] = values[i];
eprintf("i is %i", i);
}
search(value, searcharray, start);
}
if (value < a)
{
int searcharrayb[start];
for (int k = 0; k < start; k++)
{
searcharrayb[k] = values[k];
eprintf("k is %i", k);
}
search(value, searcharrayb, start);
}
}
}
return false;
}
【问题讨论】:
-
当你重新调用 search() 时,你应该使用 return search()
-
if声明是不必要的。您必须确定它的工作范围。奇偶校验在这里没有出现。 -
当然可以。程序从调用堆栈中恢复。一旦
search(value, searcharray, start);完成评估,它将继续执行您的程序。因此return false;被执行。 -
您不应该使用名为
l的变量,很难看出与1的区别。 -
我已将运行递归的那部分代码更改为:
if (search(value, searcharray, start)== true){ return true; }else{ return false;