binary search on c, the while loop

13,247

Take a simple case of

int a[1] = {5};
printf("%d\n", binarySearch(a, 1, 5));

With while(low < high), code prints -1 (did not find - wrong answer).

With while(low <= high), code prints 0 (found - right answer).

Share:
13,247
shira
Author by

shira

Updated on June 27, 2022

Comments

  • shira
    shira almost 2 years

    There's something that I don't get with the binary search code on C.

    int binarySearch(int a[], int n, int x)
    {
       int low=0, mid, high=n-1;
       while(low <= high)
       {
            mid = (low + high) / 2;
            if (x < a[mid])
                high = mid - 1;
            else if (x > a[mid])
             low = mid + 1;
           else
             return mid;
       }
       return -1;
    }
    

    Why does the while loop while(left<=right) can't be written: while(left<right)? Will this change effect things?