C recursive function won't return true

前端 未结 1 1096
别那么骄傲
别那么骄傲 2021-01-28 05:11

I have a search function which employs recursion to perform a binary search of an array, values[], for a value:

int recurseSearch(int v         


        
相关标签:
1条回答
  • 2021-01-28 05:39

    I have not looked carefully at your code so there might be other bugs in it, but it sounds like you want the return value from the deepest recursive call to be passed up the stack all the way to the caller. In that case, you would remove the return 3; and simply return the value of each the recursive call you are making:

    int recurseSearch(int value, int values[], int min, int max) {
    
        if (value > values[max] || min > max) return 1;
    
        int midpoint = (max+min)/2;
    
        if (values[midpoint] > value)
            //search in left
            return recurseSearch(value, values, min, midpoint);
    
        else if (values[midpoint] < value)
            //search in right
            return recurseSearch(value, values, midpoint, max);
    
        else if (values[midpoint] == value)
            return 0;
    
        else 
            return 2;
    }
    

    The way you originally wrote your code, the return values from the recursive calls were being ignored entirely, and the return 3; statement would be executed instead.

    0 讨论(0)
提交回复
热议问题