Problem solving with programming: Finding a number in a sorted array with the least difference from given number
Given a sorted array and a value, we have to find the closest value (with least difference).
Read full article from Problem solving with programming: Finding a number in a sorted array with the least difference from given numberpublic static int getLeastDiffNum(int[] array, int num){int low = 0;int high = array.length - 1;int mid = (low + high) / 2;int minDiff = Integer.MAX_VALUE;int result = array[mid];while ( low <= high ){mid = (low + high) / 2;int diff = Math.abs( array[mid] - num );if( diff == 0 ){result = array[mid];break;}else{if( diff < minDiff ){result = array[mid];minDiff = diff;}}if( array[mid] > num )high = mid - 1;elselow = mid + 1;}return result;}