Binary Search汇总

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

 

posted @ 2015-05-05 08:11  xiaomaoliu  阅读(108)  评论(0编辑  收藏  举报