get closest value to a number in array

I have an array of positive/negative ints

int[] numbers = new int[10];
numbers[0] = 100;
numbers[1] = -34200;
numbers[2] = 3040;
numbers[3] = 400433;
numbers[4] = 500;
numbers[5] = -100;
numbers[6] = -200;
numbers[7] = 532;
numbers[8] = 6584;
numbers[9] = -945;

Now, I would like to test another int against this array, and return the number that is closest to the int.

For example if I used the number 490 i would get back item #4 from numbers 500 what is the best way to do something like this?

int myNumber = 490;
int distance = 0;
int idx = 0;
for(int c = 0; c < numbers.length; c++){
    int cdistance = numbers[c] - myNumber;
    if(cdistance < distance){
        idx = c;
        distance = cdistance;
    }
}
int theNumber = numbers[idx];

That doesn't work. Any suggestions on a good method to do this?


int myNumber = 490;
int distance = Math.abs(numbers[0] - myNumber);
int idx = 0;
for(int c = 1; c < numbers.length; c++){
    int cdistance = Math.abs(numbers[c] - myNumber);
    if(cdistance < distance){
        idx = c;
        distance = cdistance;
    }
}
int theNumber = numbers[idx];

Always initialize your min/max functions with the first element you're considering. Using things like Integer.MAX_VALUE or Integer.MIN_VALUE is a naive way of getting your answer; it doesn't hold up well if you change datatypes later (whoops, MAX_LONG and MAX_INT are very different!) or if you, in the future, want to write a generic min/max method for any datatype.


In Java 8:

List<Integer> list = Arrays.stream(numbers).boxed().collect(Collectors.toList());

int n = 490;

int c = list.stream()
            .min(Comparator.comparingInt(i -> Math.abs(i - n)))
            .orElseThrow(() -> new NoSuchElementException("No value present"));

Initially, you can use a List instead of an Array (lists have much more functionality).


you are very close. I think the initial value of 'distance' should be a big number instead of 0. And use the absolute value for the cdistance.


cdistance = numbers[c] - myNumber. You're not taking the absolute value of the difference. If myNumber is a lot greater than numbers[c] or if numbers[c] is negative, the comparison will register as the "minimum difference".

Take for example the case where numbers[c] = -34200. numbers[c] - myNumber would then be -34690, a lot less than the distance.

Also, you should initialize distance to a large value, as no solution has been found at the start.


You can tweak the good old binary search and implement this efficiently.

Arrays.sort(numbers);
nearestNumber = nearestNumberBinarySearch(numbers, 0, numbers.length - 1, myNumber);

private static int nearestNumberBinarySearch(int[] numbers, int start, int end, int myNumber) {
    int mid = (start + end) / 2;
    if (numbers[mid] == myNumber)
        return numbers[mid];
    if (start == end - 1)
        if (Math.abs(numbers[end] - myNumber) >= Math.abs(numbers[start] - myNumber))
            return numbers[start];
        else
            return numbers[end];
     if(numbers[mid]> myNumber)
        return nearestNumberBinarySearch(numbers, start,mid, myNumber);
     else
         return nearestNumberBinarySearch(numbers,mid, end, myNumber);

}