2
我试图创建一个二进制搜索算法,并已使用两组if语句,当样本是偶数/不均匀。不均匀侧当前工作按计划返回true,偶数侧返回true,但随后转移到“一网打尽”,在功能底部的代码并返回false:代码似乎继续运行后返回语句(在C)
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() – webbi
'if'语句是不必要的。你必须确定它的工作范围。平价不会在这里出现。 – coderredoc
当然是的。程序从调用栈中恢复。一旦搜索(价值,搜索,开始);评估它将继续下去你的程序。因此'执行返回false;'。 – JustinJmnz