Search code examples
binary-search

Confuse in Binary Search when to use left < right ; left <= right ; and few more


I've difficulty in understanding when to use:

while (left < right ) {
}

vs when to use:

while (left <= right ) {
}

Also while setting left and right boundaries sometimes we use:

left = mid 

and sometime we use

left = mid + 1;

similarly

right = mid; vs
right = mid - 1;

Is there any fundamental I am missing in knowledge of Binary search ?


Solution

  • The basic idea is to search and find the element:

    public static int indexOf(int[] array, int target) {
       int lo = 0, hi = a.length - 1;
       while (lo <= hi) {
          // Key is in a[lo..hi] or may be it is not present.
          int mid = lo + (hi - lo) / 2;
          if      (target < a[mid]) hi = mid - 1;
          else if (target > a[mid]) lo = mid + 1;
          else return mid;
       }
       return -1;
    }
    

    We can also use mid = (lo + hi) >>> 1 to compute the mid but using (lo+hi)/2 may cause overflow. Now the confusion part:

    We use while (lo <= hi) if we are returning the match from inside the loop. We use while (lo < hi) when we want to exit the loop first and then use the result of lo or hi to return the match.

    Good intro for binary search use cases: https://leetcode.com/discuss/general-discussion/786126/Python-Powerful-Ultimate-Binary-Search-Template.-Solved-many-problems