get closest value to a number in array

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.

Leave a Comment