二分查找实现取近似值
需求
找出数组中与当前值近似的值
实现
public static double near(double[] arr, double value) {
if (value > arr[arr.length-1]){
return arr[arr.length-1];
}
if (value < arr[0]){
return arr[0];
}
int left = 0;
int right = arr.length - left;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] > value) {
if (value > arr[mid-1]){
return arr[mid] - value > value-arr[mid-1] ? arr[mid-1] :arr[mid];
}
// 向左边查找
right = mid - 1;
}else{
if (value < arr[mid+1]){
return arr[mid+1] - value > value-arr[mid] ? arr[mid] :arr[mid+1];
}
// 向右边查找
left = mid + 1;
}
}
return 0;
}