0

I am having some serious issues figuring out what is wrong with my code. I have run this through on paper with the simplest of numbers and cant seem to understand why it fails. I could use some direction in what I have missed.

here is the relevant code...

bool search(int value, int values[], int n)
{
int min = 0, max = (n - 1), mid = ((max + min) / 2);
while (min <= max)
{
    if (values[mid] == value)
        return true;
    else if (values[mid] > value)
    {
        max = (mid - 1);
        mid = ((max + min) / 2);
    }
    else if (values[mid] < value)
    {
        min = (mid + 1);
        mid = ((max + min) / 2);
    }
    else 
    {
        return false;
    }
}
return false;
}

here is the output... sh-4.3$ ./find 2
haystack[0] = 0
haystack[1] = 1
haystack[2] = 2
haystack[3] =
Didn't find needle in haystack.

1 Answer 1

1

I tested your search code and it's working fine. Binary search is dependent on the list being a sorted list. If the list isn't sorted, the search may or may not work.

You should verify that your sort is working correctly. Use the same data that you are using for your search tests. Also, temporarily add a routine at the very end of your sort routine to print out the list in order. This will tell you what's going on with your sort.

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

1
  • Thanks! you were right my problem was in my sorting function! sorry for making you chase ghosts in my searching function.
    – Brandon
    Commented Oct 16, 2015 at 16:37

You must log in to answer this question.

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