Find closest number in array in C++


Suppose we have an array A with n elements. And elements are sorted. We have to find the closest value to the given integer. The array may contain duplicate values and negative numbers. So if the array is like [2, 5, 6, 7, 8, 8, 9] and the target number is 4, then closest element is 5.

We can solve this by traversing through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolute difference.

Example

 Live Demo

#include<iostream>
#include<list>
using namespace std;
int getNearest(int x, int y, int target) {
   if (target - x >= y - target)
      return y;
   else
      return x;
}
int getNearestElement(int arr[], int n, int target) {
   if (target <= arr[0])
      return arr[0];
   if (target >= arr[n - 1])
      return arr[n - 1];
   int left = 0, right = n, mid = 0;
   while (left < right) {
      mid = (left + right) / 2;
      if (arr[mid] == target)
         return arr[mid];
      if (target < arr[mid]) {
         if (mid > 0 && target > arr[mid - 1])
            return getNearest(arr[mid - 1], arr[mid], target);
            right = mid;
      } else {
         if (mid < n - 1 && target < arr[mid + 1])
            return getNearest(arr[mid], arr[mid + 1], target);
         left = mid + 1;
      }
   }
   return arr[mid];
}
int main() {
   int arr[] = { 2, 5, 6, 7, 8, 8, 9 };
   int n = sizeof(arr) / sizeof(arr[0]);
   int target = 4;
   cout << "Nearest element of " << target << " is: " << getNearestElement(arr, n, target);
}

Output

Nearest element of 4 is: 5

Updated on: 17-Dec-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements