代码似乎在return语句后继续运行(在C中)

时间:2017-10-17 19:56:20

标签: c algorithm return

我正在尝试创建二进制搜索算法,并且在样本均匀/不均匀时使用了两组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;
}

1 个答案:

答案 0 :(得分:2)

您的代码如下所示:

search(...)
{ 
    if(cond)
        return false
    if(cond)
        return true
    else
        search(...)
    return false
}

您需要将其更改为:

search(...)
{ 
    if(cond)
        return false
    if(cond)
        return true
    else
        return search(...)
}

请注意在递归调用搜索之前的额外回报