Binary search doesn't seem to find the element in middle.

int binary_search(int value, int values[], int n) {
    int low = 0;
    int high = n-1;
    while( high >= low )
        int mid = (high + low) / 2;

        if ( values[mid] == value ) {
            return mid;

        if ( values[mid] > value ) {
            high = mid -1;
        } else if ( values[mid] < value ) {
            low = mid +1;
    return -1;

:( finds 42 in {41,42,43} \ expected an exit code of 0, not 1

link to check50

Binary search

1 Answer 1


In testing, the code works fine. Is it possible that you have a problem with your sort function? Have you verified that sort is correct by printing out the sorted list with different test data?

As a side note, I am curious why you decided to write binary_search() the way you did. Specifically, search returns a bool, while binary_search returns an int. Your binary_search could easily just return a bool instead of an int by replacing the return type and returning true or false instead of a number. In short, it could have been directly written as search() instead of calling another function from search(). Yes, it works, but why introduce an additional function when you don't have to?

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

  • Thanks for the reply. I'll check if there is anything wrong with the sort function. Yes, I don't need the extra binary_search function. It was there because I tried to implement binary search recursively at first.
    – Anandu
    Commented Sep 28, 2016 at 2:12
  • Yes. It was a silly problem with my implementation of selection sort.
    – Anandu
    Commented Sep 28, 2016 at 2:19

You must log in to answer this question.

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