Binary Search

Share on:

Binary Search Overview

Code

  • 其中 int mid = left + (right - left) / 2 不直接使用 (left + right) / 2 因为若left + right 大于int的上限会出错,不过也可以用位操作替代 (left + right) >> 1;
  • 此外这样取了之后中间点偏左
 1	public int search(int[] nums, int target) {
 2	    int N = nums.length;
 3	    int left = 0, right = N - 1;
 4	    while (left <= right){
 5	        int mid = left + (right - left) / 2;
 6	        if (nums[mid] < target){
 7	            left = mid + 1;
 8	        }else if (nums[mid] > target){
 9	            right = mid - 1;
10	        }else{
11	            return mid;
12	        }
13	    }
14	    return -1;
15	}
16
17// OR
18
19	while (left + 1 < right){
20	    int mid = left + (right - left) / 2;
21	    if (nums[mid] > nums[left]){
22	        left = mid;
23	    }else{
24	        right = mid;
25	    }
26	}
27	// check boundary