0

I've been pulling my hair out over this for a few days now, the plus side of which being that I've really pruned and cut down my code to what seems strictly necessary to figure out the issue.

Performing the suggested test, ./generate 1000 50 | ./find 127, always returns a "needle not found" result. I've been going over my code, as well as looking online, but can't seem to figure out why this is happening.

I'm also not sure of the syntax for using GDB with a double-file set-up like we have here with generate.c and find.c, so I haven't been able to debug that way.

Could anyone point me in the right direction?

/**
 * Binary search
 */

bool binarysearch(int value, int values[], int min, int max)
{
    int mid = (max+min)/2;

    if ( max < min )
    {
        return false;
    }   
    else if ( value == values[mid] )
    {   
        return true;
    }
    else if ( value < values[mid] )
    {       
        return binarysearch( value, values, min, mid - 1 );
    }
    else if ( value > values[mid] )
    {    
        return binarysearch( value, values, mid + 1, max );
    }
    else
    {
        return false;
    }

}

/**
 * Returns true if value is in array of n values, else false.
 */
bool search(int value, int values[], int n)
{
    // If a array of negative size is requested, gives error code
    if (n < 0)
    {
        printf("Invalid number of values.\n");
        return -1;
    }

    int min = 0;
    int max = n;

    return binarysearch(value, values, min, max);

}
  • Perhaps you're looking in the wrong haystack. ;-) I ran your code and it works fine. I believe that it is more likely to be a problem with your sort routine. Have you verified that it is working correctly? – Cliff B Oct 14 '15 at 16:22
  • Oh, poop. I forgot that I never verified my sort routine! Thanks for the wake up call, time to begin anew my debugging process. – Jonathan Oct 14 '15 at 17:13
1

Perhaps you're looking in the wrong haystack. ;-) I ran your code and it works fine. I believe that it is more likely to be a problem with your sort routine. Have you verified that it is working correctly? – Cliff B 1 hour ago

Oh, poop. I forgot that I never verified my sort routine! Thanks for the wake up call, time to begin anew my debugging process. – Jonathan Allenby 43 mins ago

Asked and answered. Cliffb.

If this answers your question, please click on the check to accept. Let's keep up on forum housekeeping. ;-)

| improve this answer | |
  • Thanks for the prompt - first time using stackexchange – Jonathan Oct 14 '15 at 18:04
  • The question still needed an actual answer posted to be accepted in order to close it out. ;-) – Cliff B Oct 14 '15 at 18:06
  • Fixed the sort code; I was storing "min" instead of values[min]. All this time... – Jonathan Oct 14 '15 at 18:35

You must log in to answer this question.

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