#K5326. Closest Element Finder
Closest Element Finder
Closest Element Finder
Given a sorted array \(arr\) of \(N\) integers and a target integer \(X\), your task is to find the array element that is closest to \(X\). If more than one element have the same minimal absolute difference with \(X\), return the smallest among them.
Task: Implement an efficient algorithm to search for the closest element, taking advantage of the sorted order of the array. A binary search based approach is recommended with an overall time complexity of \(O(\log N)\).
Note: The input is provided via stdin and the output should be printed to stdout.
Examples:
Input: 5 1 2 4 8 16 7 Output: 8</p>Input: 6 1 2 3 4 5 15 10 Output: 5
inputFormat
The input consists of three lines:
- The first line contains an integer \(N\), the number of elements in the array.
- The second line contains \(N\) space-separated integers representing the sorted array \(arr\).
- The third line contains an integer \(X\), the target value.
You should read input from stdin
.
outputFormat
Output a single integer: the element in the array that is closest to \(X\). In case of a tie, output the smallest element.
The answer should be printed to stdout
.
5
1 2 4 8 16
7
8
</p>