Find closest number from array to the given number in Java

In this tutorial we will find closest number from array to the given number. Given an array of sorted integers, find the closest value to the given number. The array may contain duplicate values and negative numbers.

Examples

Array : 2,5,6,7,8,8,9
Target number : 5
Output : 5

Target number : 11
Output : 9

Target Number : 4
Output : 5

Find Closest Number

The below code will find the closest number from the array of integers.

package com.roytuts.java.closest.number.in.array;

public class ClosestToTargetNumber {

	public static void main(String[] args) {
		int[] arr = new int[] { 2, 5, 6, 7, 8, 8, 9 };

		System.out.println(findClosest(arr, 5));
		System.out.println(findClosest(arr, 11));
		System.out.println(findClosest(arr, 4));
	}

	public static int findClosest(int[] arr, int target) {
		int idx = 0;
		int dist = Math.abs(arr[0] - target);

		for (int i = 1; i< arr.length; i++) {
			int cdist = Math.abs(arr[i] - target);

			if (cdist < dist) {
				idx = i;
				dist = cdist;
			}
		}

		return arr[idx];
	}

}

The above program will produce the below output:

5
9
5

Thanks for reading.

Related posts

Leave a Comment