Skip to content

Instantly share code, notes, and snippets.

@ravichandrae
Created October 15, 2013 02:38
Show Gist options
  • Save ravichandrae/6985691 to your computer and use it in GitHub Desktop.
Save ravichandrae/6985691 to your computer and use it in GitHub Desktop.
This program finds the closest number in the given sorted array
/**
* Created with IntelliJ IDEA.
* User: Ravi
* Date: 10/15/13
* Time: 7:09 AM
* To change this template use File | Settings | File Templates.
*/
public class FindLeastDiffNumArray {
public static void main(String[] args)
{
int [] array1 = {1,3,5,7,9,11,13,15};
int [] array2 = {-23, -9, 0, 7, 15, 38, 46};
System.out.println( getLeastDiffNum(array1, 10) );
System.out.println( getLeastDiffNum(array1, 13) );
System.out.println( getLeastDiffNum(array2, 4) );
System.out.println( getLeastDiffNum(array2, 35) );
}
public 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;
else
low = mid + 1;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment