查找数组中最接近目标数的数--折半查找法
/**
* 查找最接近目标值的数,并返回 索引
* @param array
* @param mutiple
* @return
*/
public static Integer binarysearchKey(Object[] array, float mutiple) {
Arrays.sort(array);
int left = 0, right = 0;
for (right = array.length - 1; left != right;) {
int midIndex = (right + left) / 2;
int mid = (right - left);
Float midValue = Float.valueOf(array[midIndex].toString());
if (mutiple == midValue) {
return midIndex;
}
if (mutiple > midValue) {
left = midIndex;
} else {
right = midIndex;
}
if (mid <= 2) {
break;
}
}
System.out.println("要查找的数:" + mutiple + "最接近的数:" +(Math.abs(Float.valueOf(array[right].toString()) -mutiple) > Math.abs(Float.valueOf(array[left].toString()) -mutiple) ? array[left] : array[right]));
return (Integer) (Math.abs(Float.valueOf(array[right].toString()) -mutiple) > Math.abs(Float.valueOf(array[left].toString()) -mutiple) ? left: right);
} |