Search code examples
cfunctionreturnbinary-search

Why does this function return -1?


I have to run a code in C. The code creates a function for binary search. So it just reads a number for the size of an array and a number x and returns its position on the array. The code is:

long int binary(long int v[], long int n, long int x){

    long int low = 0, high = n-1, mid;

    while(low<=high){

        mid = (high+low)/2;

        if(x<v[mid]){
            high = mid - 1;}

        else if(x>v[mid]){
            low = mid + 1;}

        else{
            return(mid);}
    }
    return(-1);
}

I don't know if I fully understand this. What I understood is:

If x is less than the number on the array on position mid, it changes the value high.

If x is greater than the number on the array on position mid, it changes the value low.

And if x is equal to the number on the array on position mid, it ends the function and returns the value mid for the position of the wanted number.

I don't think I get that return(-1) in the end. Does it mean that the code couldn't find the position for the wanted number and returned a negative values as a way of saying there's something wrong?


Solution

  • You are right. Every iteration when x is not equal to v[mid], either the low index increases or the high index decreases. If x is not present in the array v, at some point the value of low will exceed high. Then, the loop breaks, and the function returns -1.