标签:
Binary Search:二分查找
实现方式:recursive or iterative
注意问题,终止循环条件,移动start,end时边界值,start = mid,end = mid
Template:
1. 在排序的数组中找A[i] == i的index,有重复元素存在. (cc150 Question 9.3)
因为有重复元素,所以例如:
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 }
标签:
原文地址:http://www.cnblogs.com/xiaomaoliu/p/4478155.html