此文转自博客http://blog.csdn.net/huoyunshen88/article/details/8567970, 自己学习标记下,感谢博主。
/**
* 查找出最接近目标值的数,并返回。
* @param array
* @param targetNum
* @return
*/
- public static int binarysearchKey(Object[] array, int targetNum) {
-
- //Object[] array = temp.clone();
- Arrays.sort(array);
- for (int i = 0; i < array.length; i++) {
- System.out.println(array[i]);
- }
- int targetindex = 0;
- int left = 0,right = 0;
- for (right = array.length-1; left!=right;) {
- int midIndex = (right + left)/2;
- int mid = (right - left);
- int midValue = (Integer) array[midIndex];
- if (targetNum == midValue) {
- return midIndex;
- }
-
- if(targetNum > midValue){
- left = midIndex;
- }else{
- right = midIndex;
- }
-
- if (mid <=1) {
- break;
- }
- }
- int rightnum = ((Integer) array[right]).intValue();
- int leftnum = ((Integer) array[left]).intValue();
- int ret = Math.abs((rightnum - leftnum)/2) > Math.abs(rightnum -targetNum) ? rightnum : leftnum;
- System.out.println("和要查找的数:"+targetNum+ "最接近的数:" + ret);
- return ret;
- }
- public static void main(String[] args) {
- ArrayList array = new ArrayList();
- array.add(26);
- array.add(76);
- array.add(46);
- array.add(76);
- array.add(54);
- array.add(94);
- array.add(24);
- array.add(34);
-
- int targetNum= 74;
- System.out.println("和要查找的数:"+targetNum+ "最接近的数:"+binarysearchKey(array.toArray(), targetNum));
-
- }
/**
* 遍历数组和要查找的数值做差,以差:数组索引存为map,然后对以差为key的数组排序,拿到差最小的索引。
* @param array
* @param num
* @return
*/
- public static Integer searchKey(int[] array,int num) {
-
- int[] temp = new int[array.length];
- Map<Integer,Integer> map = new TreeMap<Integer,Integer>();
- int disnum = 0;
- for (int i = 0; i < array.length; i++) {
- disnum = Math.abs(array[i] - num);
- temp[i]=disnum;
- map.put(disnum, i);
- }
- System.out.println("数组和的差值和数组元素的差值相减的绝对值和位置的映射结果:" + map);
- Arrays.sort(temp);
- Integer index = map.get(temp[0]);
- System.out.println("数组和的差值和数组元素的差值相减的绝对值最小值:"+temp[0]+"最小值的key:" + array[index]);
- return (Integer) array[index];
- }
/**
* 求一个数组的最大值
* @param array1
*/
- public static void max1(int[] array1) {
- int max = 0;
- for (int i : array1) {
- max = Math.max(max, i);
- }
- System.out.println("数组最大值是:"+max);
- }
/**
* 求一个数组的最大值
* @param array1
*/
- public static void max2(int[] array1) {
- int max = 0;
- for (int i = 0; i < array1.length; i++) {
- max = max > array1[i] ? max : array1[i];
- }
- System.out.println("数组最大值是:"+max);
- }
/**
* 求一个数组的最大值
* @param array1
*/
- public static void max3(int[] array1) {
- Arrays.sort(array1);
- System.out.println("数组最大值是:"+array1[array1.length-1]);
- }
//计算最小值
private BigDecimal calMinValue(BigDecimal[] arrays){
BigDecimal temp = new BigDecimal("0");
for(int i=arrays.length;--i>=0;){
for(int j=0;j<i;j++){
if(arrays[j].compareTo(arrays[j+1])==1)
{
temp=arrays[j];
arrays[j]=arrays[j+1];
arrays[j+1]=temp;
}
}
}
for(int n=0;n<arrays.length;n++){
temp = arrays[0];
break;
}
return temp;
}