I'm having some difficulty implementing binary search. I wrote linear search with no problems but when I compile my code for binary search, I get an error. I decided to take the iterative approach just because it wasn't comfortable for me to nest a recursive function inside of the search function.

bool search(int value, int values[], int n)
    // implement a searching algorithm (binary)
    int min = 0;
    int max = n;
    int middle = (min + max) / 2;
    while(min <= max)
        if(values[middle] > values)
            max = middle - 1;
        else if(values[middle] < values)
            min = middle + 1;
        else if(values[middle] == values)
            return true;
    return false;

and the error that I'm getting is: enter image description here

1 Answer 1


It's what you are comparing that is giving you issues. You are comparing an array element to the array itself, values[x] > values. Or, to put it another way, you have the same typo (or a cut and paste error) in three different places.

Try using value instead of values as specified in the function signature bool search(int value, int values[], int n)

As soon as you finish saying "Doh!" like every other programmer in history (you're in good company ;-) ), and if this answers your question, please accept this answer to remove it from the unanswered question pool. Let's keep up on forum maintenance. ;-)

  • Yes. Doh indeed. Jun 16, 2015 at 6:32
  • I don't understand , how (min+max)/2 gives the middle number? Sep 10, 2015 at 9:13
  • My code is very similar to this one (minus the errors and a different variable), but it's not working and I don't know what I did wrong! I've already checked my sort and it seems to be working fine, so the problem must be in my search code. What I've noticed is that this last return false makes my code ALWAYS return false (because if I change it to true, it always returns true). I don't know what to do... @CliffB Mar 23, 2016 at 14:59

You must log in to answer this question.

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