Java Program to Find closest number in array
Last Updated :
13 Apr, 2023
Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers.
Examples:
Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9}
Target number = 11
Output : 9
9 is closest to 11 in given array
Input :arr[] = {2, 5, 6, 7, 8, 8, 9};
Target number = 4
Output : 5
A simple solution is to traverse through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolution difference.
An efficient solution is to use Binary Search.
Java
// Java program to find element closest to given target.
import java.util.*;
import java.lang.*;
import java.io.*;
class FindClosestNumber {
// Returns element closest to target in arr[]
public static int findClosest(int arr[], int target)
{
int n = arr.length;
// Corner cases
if (target <= arr[0])
return arr[0];
if (target >= arr[n - 1])
return arr[n - 1];
// Doing binary search
int i = 0, j = n, mid = 0;
while (i < j) {
mid = (i + j) / 2;
if (arr[mid] == target)
return arr[mid];
/* If target is less than array element,
then search in left */
if (target < arr[mid]) {
// If target is greater than previous
// to mid, return closest of two
if (mid > 0 && target > arr[mid - 1])
return getClosest(arr[mid - 1],
arr[mid], target);
/* Repeat for left half */
j = mid;
}
// If target is greater than mid
else {
if (mid < n-1 && target < arr[mid + 1])
return getClosest(arr[mid],
arr[mid + 1], target);
i = mid + 1; // update i
}
}
// Only single element left after search
return arr[mid];
}
// Method to compare which one is the more close
// We find the closest by taking the difference
// between the target and both values. It assumes
// that val2 is greater than val1 and target lies
// between these two.
public static int getClosest(int val1, int val2,
int target)
{
if (target - val1 >= val2 - target)
return val2;
else
return val1;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 2, 4, 5, 6, 6, 8, 9 };
int target = 11;
System.out.println(findClosest(arr, target));
}
}
Output:
9
Time Complexity: O(log(n))
Auxiliary Space: O(log(n)) (implicit stack is created due to recursion)
Approach 2: Using Two Pointers
Another approach to solve this problem is to use two pointers technique, where we maintain two pointers left and right, and move them towards each other based on their absolute difference with target.
Below are the steps:
- Initialize left = 0 and right = n-1, where n is the size of the array.
- Loop while left < right
- If the absolute difference between arr[left] and target is less than or equal to the absolute difference between arr[right] and target, move left pointer one step to the right, i.e. left++
- Else, move right pointer one step to the left, i.e. right–-
- Return arr[left], which will be the element closest to the target.
Below is the implementation of the above approach:
Java
// Java program to find element
// closest to given target using two pointers
import java.util.*;
public class GFG {
public static int findClosest(int[] arr, int n,
int target)
{
int left = 0, right = n - 1;
while (left < right) {
if (Math.abs(arr[left] - target)
<= Math.abs(arr[right] - target)) {
right--;
}
else {
left++;
}
}
return arr[left];
}
public static void main(String[] args)
{
int[] arr = { 1, 2, 4, 5, 6, 6, 8, 8, 9 };
int n = arr.length;
int target = 11;
System.out.println(findClosest(arr, n, target));
}
}
// This code is contributed by Susobhan Akhuli
Time Complexity: O(N), where n is the length of the array.
Auxiliary Space: O(1)
Please refer complete article on Find closest number in array for more details!
Similar Reads
Java Program for Ceiling in a sorted array Given a sorted array and a value x, the ceiling of x is the smallest element in array greater than or equal to x, and the floor is the greatest element smaller than or equal to x. Assume than the array is sorted in non-decreasing order. Write efficient functions to find floor and ceiling of x. Examp
4 min read
Java Program to Print the kth Element in the Array We need to print the element at the kth position in the given array. So we start the program by taking input from the user about the size of an array and then all the elements of that array. Now by entering the position k at which you want to print the element from the array, the program will print
2 min read
Program For Closest Prime Number Given a number N, you have to print its closest prime number. The prime number can be lesser, equal, or greater than the given number. Condition: 1 ⤠N ⤠100000 Examples: Input : 16 Output: 17 Explanation: The two nearer prime number of 16 are 13 and 17. But among these, 17 is the closest(As its dis
10 min read
Java Program to Print the Smallest Element in an Array Java provides a data structure, the array, which stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. Example: arr1[] = {2 , -1 , 9 , 10} output : -1 arr2[] = {0, -10, -13, 5} output : -13 We need to find and print the smallest value
3 min read
Java Program to Find the smallest missing number Given a sorted array of n distinct integers where each integer is in the range from 0 to m-1 and m > n. Find the smallest number that is missing from the array. Examples Input: {0, 1, 2, 6, 9}, n = 5, m = 10 Output: 3 Input: {4, 5, 10, 11}, n = 4, m = 12 Output: 0 Input: {0, 1, 2, 3}, n = 4, m =
5 min read
Finding Minimum Element of Java Vector Vector implements a dynamic array that means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index. We know two ways for declaring array i.e. either with a fixed size of array or size enter as per the demand of the user according to whic
3 min read
Java Program To Recursively Linearly Search An Element In An Array Given an array arr[] of n elements, write a recursive function to search for a given element x in the given array arr[]. If the element is found, return its index otherwise, return -1.Input/Output Example:Input : arr[] = {25, 60, 18, 3, 10}, Element to be searched x = 3Output : 3 (index )Input : arr
3 min read
Sort and Search an Element in Java In Java sorting and searching an element in an array is very easy. Unlike C, where we have to make all the functions to work, Java has inbuilt functions to do the same work. To sort an array there is a sort function and to search an element in a sorted array there is a binarySearch() function. To le
3 min read
Java Program for Minimum product pair an array of positive Integers Given an array of positive integers. We are required to write a program to print the minimum product of any two numbers of the given array.Examples: Input : 11 8 5 7 5 100 Output : 25 Explanation : The minimum product of any two numbers will be 5 * 5 = 25. Input : 198 76 544 123 154 675 Output : 934
4 min read
Java Program for Linear Search Linear Search is the simplest searching algorithm that checks each element sequentially until a match is found. It is good for unsorted arrays and small datasets.Given an array a[] of n elements, write a function to search for a given element x in a[] and return the index of the element where it is
2 min read