Find the Closest Number in the Array
Get an
array of Integers arr[] with size n and target element e. Apply Linear Search / Binary Search
to find closest element to target element e
in the array arr[]. Print the
closest element. The array may contains negative numbers. If more than one
element is closer, print the smaller one.
Examples
Input
1:
5
5
7 9 3 9
4
Output
1:
3
Input
2:
5
5
7 9 10 13
14
Output
2:
13
Try your Solution
Strongly recommended to Solve it on your own, Don't directly go to the solution given below.
Program or Solution
import java.util.*;
class Closest
{
public static void main(String args[])
{
//Variable and Object Declarations
Scanner input = new Scanner(System.in);
int n,e,count=0;
//Getting size of Array & Declare Array arr[]
n = input.nextInt();
int arr[] = new int[n];
//Get n values to array arr[]
for(int i = 0; i<n; i++)
{
arr[i] = input.nextInt();
}
e = input.nextInt();
//Linear Search
int min_diff = Math.abs(e-arr[0]);
int closest = arr[0];
for(int i = 0; i<n; i++)
{
int diff = Math.abs(e-arr[i]);
if(diff < min_diff)
{
min_diff = diff;
closest = arr[i];
}
else if(diff == min_diff)
{
if(arr[i] < closest)
{
closest = arr[i];
}
}
}
System.out.print(closest);
}
}