首页 > 其他 > 详细

正确的二分查找实现

时间:2015-10-25 13:41:16      阅读:306      评论:0      收藏:0      [点我收藏+]
   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;
    }

 

正确的二分查找实现

原文:http://www.cnblogs.com/marsbible/p/4908605.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!