Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8189786

Enhancement of binarysearch() for int arrays

XMLWordPrintable

      A DESCRIPTION OF THE REQUEST :
      private static int binarySearch0(int[] a, int fromIndex, int toIndex,
      int key) {
      int low = fromIndex;
      int high = toIndex - 1;

      while (low <= high) {
      int mid = (low + high) >>> 1;
      int midVal = a[mid];

      if (midVal < key)
      low = mid + 1;
      else if (midVal > key)
      high = mid - 1;
      else
      return mid; // key found
      }
      return -(low + 1); // key not found.
      }

      JUSTIFICATION :
      for ex int[] a={1,2...........100};
      and I am searching elements that is not in the range of this array. for ex: 199
      but it still executes while loop multiple time

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Actual behavior should be like this without executing while loop

      -1
      ACTUAL -
      elements is out of range of array but still executing while loop

      LOW:0>>>>>>>>>HIGH::54
      LOW:28>>>>>>>>>HIGH::54
      LOW:42>>>>>>>>>HIGH::54
      LOW:49>>>>>>>>>HIGH::54
      LOW:52>>>>>>>>>HIGH::54
      LOW:54>>>>>>>>>HIGH::54
      -56

      ---------- BEGIN SOURCE ----------
      private static int binarySearch0(int[] a, int fromIndex, int toIndex,
      int key) {
      int low = fromIndex;
      int high = toIndex - 1;
                      
      // we can add below if condition
      if(key>a[a.length-1])
      return -(low+1);
      // end

      while (low <= high) {
      int mid = (low + high) >>> 1;
      int midVal = a[mid];

      if (midVal < key)
      low = mid + 1;
      else if (midVal > key)
      high = mid - 1;
      else
      return mid; // key found
      }
      return -(low + 1); // key not found.
      }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Required to add below line ::

      // we can add below if condition
      if(key>a[a.length-1])
      return -(low+1);
      // end

            Unassigned Unassigned
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: