标签:blog ar java sp div 问题 log bs line
在java中为了避免 low+high溢出,可以用无符号右移:正数高位补0,负数高位补1
int mid = (low + high) >>> 1;
如果是在c++中,那么需要先转换为unsigned的再移位
int a=100;
int b;
b=((unsigned int)a)>>1;
或者 int mid = low + ((high - low) / 2);
public static int binarySearch(int[] a, int target) { int low = 0; int high = a.length - 1; while (low <= high) { int mid = (low + high) >>> 1; int midVal = a[mid]; if (midVal < target) low = mid + 1; else if (midVal > target) high = mid - 1; else return mid; } return -1; }
标签:blog ar java sp div 问题 log bs line
原文地址:http://www.cnblogs.com/juandx/p/4083391.html