正确的二分查找实现

   public static int binary_search(int[] A, int key, int imin, int imax)  
     {
      // continue searching while [imin,imax] is not empty
      while (imin <= imax)
      {
          // calculate the midpoint for roughly equal partition
          int imid = imin + ((imax - imin) / 2);
          if(A[imid] == key)
            // key found at index imid
            return imid; 
          // determine which subarray to search
          else if (A[imid] < key)
            // change min index to search upper subarray
            imin = imid + 1;
          else         
            // change max index to search lower subarray
            imax = imid - 1;
      }
      // key was not found
      return -1;
    }

 

posted on 2015-10-25 13:00  macrosoft  阅读(214)  评论(0编辑  收藏  举报

导航