0

I'm having trouble accessing only the left half of an array, doing the same for the right half works fine for now, at least I'm not getting any errors. I figured accessing the array using pointers would be better than creating a new array for each iteration. Below is where I think the problem lays.

int *lefthalf = values;

if (target < lefthalf[mid]) {
    lefthalf = *lefthalf / 2;
    size -= mid; // Divide size by half
}

And this is the full code:

bool search(int target, int values[], int size)
{
    int *righthalf = values;
    int *lefthalf = values;

    while (size > 0) {
        int mid = size / 2;

        if (target > righthalf[mid]) {
            righthalf = &righthalf[size];
            size -= mid; // Divide size by half
        }
        if (target < lefthalf[mid]) {
            lefthalf = *lefthalf / 2;
            size -= mid; // Divide size by half
        }
        else if (target == values[mid]) {return true;}
    }
    return false;
}

Also, even though the righthalf part is not giving errors, I have a feeling it's not going to work.

Thanks.

3

For a binary search, you keep only one range, not two. That one could be specified by either a pointer to the start of the range and a length, or a left and right index limiting the range (the version with less pointers, probably leading to safer code).

Please note that in dividing the array in half, the two halves do not necessarily have to be of equal length.

And C arrays are simply pointers to the first element, so a reference to the left half is the same as a reference to the whole array.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .