Вопрос

I have written some peace of code to implement a function, which uses binary search to check, if a given value is inside an array or not. I used a recursive function which calls itself with new inputs so that always one half of a sorted array of values gets truncated. If the binary search function evaluates to true, the previous executed functions evaluate to false. Does someone have an idea how to handle this problem?

Here's the function i've used in my code:

bool binarySearch(int key, int array[], int min, int max)
{
    int midPoint = findMidPoint(min, max);
    if (max < min)
        return false;

    if (array[midPoint] < key)
    {
        binarySearch(key, array, midPoint + 1, max);
    }
    else if (array[midPoint] > key)  
    {
        binarySearch(key, array, min, midPoint - 1);
    }
    else if (array[midPoint] == key)
    {
    return true;
    }
    return false;  
}
Это было полезно?

Решение

it is what arunmoezhi said, you need to return your calls (recursive function) if not your result will banish and the next phase is returning false thats why you always get false.

bool binarySearch(int key, int array[], int min, int max)
{
    int midPoint = findMidPoint(min, max);
    if (max < min)
        return false;

    if (array[midPoint] < key)
    {
      return  binarySearch(key, array, midPoint + 1, max);
    }
    else if (array[midPoint] > key)  
    {
       return binarySearch(key, array, min, midPoint - 1);
    }
    else if (array[midPoint] == key)
    {
    return true;
    }
    return false;  
}

Другие советы

You need to add return to the recursive calls.

bool binarySearch(int key, int array[], int min, int max)
{
    int midPoint = findMidPoint(min, max);
    if (max < min)
        return false;

    if (array[midPoint] < key)
    {
        return binarySearch(key, array, midPoint + 1, max); // Return from the call
    }
    else if (array[midPoint] > key)  
    {
        return binarySearch(key, array, min, midPoint - 1); // Return from the call
    }
    else if (array[midPoint] == key)
    {
       return true;
    }
    return false;  
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top