码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Search汇总

时间:2015-05-05 08:50:23      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

Binary Search:二分查找

实现方式:recursive or iterative

注意问题,终止循环条件,移动start,end时边界值,start = mid,end = mid

Template:

 

1. 在排序的数组中找A[i] == i的index,有重复元素存在. (cc150 Question 9.3)

因为有重复元素,所以例如:

A[mid] < mid, 不仅要search right,左边也可能出现A[i] == i
所以两边都需要Search,但是可以排除一些点
Left: start --> min{ A[mid], mid -1 } 
Right: max{ mid + 1, A[mid]} ----> end
 
技术分享
 1 /*
 2      * For question 2 elements are not distinct
 3      *search both left and right but can shrink searh area
 4      */
 5     public static int magicFast(int[] arr, int start, int end){
 6         if(end < start || start <  0 || end >= arr.length){
 7             return -1;
 8         }
 9         int midIndex = (start + end)/2;
10         int midValue = arr[midIndex];
11         
12         if(midIndex == midValue) return midIndex;
13         
14         //search left
15         int leftIndex = Math.min(midValue, midIndex - 1);
16         int left = magicFast(arr, start, leftIndex);
17         if(left >= 0) return left;
18         
19         //search right
20         int rightIndex = Math.max(midValue, midIndex + 1);
21         int right = magicFast(arr, rightIndex, end);
22         //no need to check
23         
24         return right;
25     }
View Code

 

Binary Search汇总

标签:

原文地址:http://www.cnblogs.com/xiaomaoliu/p/4478155.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!