两点理解二分法(Java语言)
2019-01-20 本文已影响0人
掌灬纹
怎样快速的理解和记住二分法
1.定前后端left,right
2.前后不相错,一直循环,每次根据中间值调整两端,或返回下标
public int binarySearch(int[] arr,int target) {
int left = 0;
int right = arr.length-1;
while(left <= right) {
int midIndex = left + ((right - left)>>1);
int midValue = arr[midIndex];
if(target > midValue) {
left = midIndex + 1;
}else if(target < midValue) {
right = midIndex - 1;
}else {
return midIndex;
}
}
return -1;
}