0

Using gdb, I found the problem is when

  1. the left_values is not there because if I try print left_values right after declaring it, it tells me No symbol "left_values" in current context.

  2. after iterating through putting values into both right and left values, if I try, say print right_values[1], it gives me some random large numbers.

Here's my code:

bool search(int value, int values[], int n)
{
    if (n < 1)
    {
        return false;
    }
    // create two subtree of values
    int isodd = 1;
    if (n % 2 == 0)
    {
        isodd = 0;
    }
    int left_values[n/2];
    int right_values[n/2];
    if (isodd)
    {
        for (int i = 0; i < n/2; i++)
        {
            left_values[i] = values[i];
        }
        for (int i = n/2+1; i < n; i++)
        {
            right_values[i] = values[i];
        }
    }
    else
    {
        for (int i = 0; i < n/2-1; i++)
        {
            left_values[i] = values[i];
        }
        for (int i = n/2; i < n; i++)
        {
            right_values[i] = values[i];
        }
    }
    n /= 2;
    // search value in values
    while (n != 0)
    {
        if (values[n] == value)
        {
            return true;
        }
        else if (values[n] > value)
        {
            search(value, left_values, n);
        }
        else
        {
            search(value, right_values, n);
        }
    }
    return false;
}

1 Answer 1

0
  1. You don´t need to test whether n is odd or even since your "odd-case" works for both cases anyway, and your "even-case" miss one index in the middle (left_values doesn´t catch index n/2-1)
  2. The recursive approach isn´t a really good choice in a scenario, where you got 3 arguments only (I don´t like it for binsearch at all, but my opinion), but for learning sake, if you want stick with recursive, you should change the search-function to a helper function that calls a binarysearch function with 4 arguments: int value, int valaues[], start, end. That way you just don´t need to make new arrays, you can stick with the original one.
  3. In GDB the cursor shows what´s going to be done next rather than what´s done yet, so i guess you was looking at the variables one step too soon, so left_values wasn´t declared yet, and right_values[1] still got the value it did get when declared which is in most cases a big random number.

You must log in to answer this question.

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