Find k closest elements to a given value in C++


Consider we have an array A with few elements. We have two other value X and k. Our task is to find the k number of nearest elements of X from the array A. If the element X is present in the array, then it will not be shown in the output. If A = [12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56] and X = 35, k = 4. The output will be 30, 39, 42, 45.

To solve this, we will use the binary search approach. Using this we will get the crossover point. If the index of the crossover point has found, we can print k-closest elements in O(k) time.

Example

#include<iostream>
using namespace std;
int getCrossoverPoint(int arr[], int left, int right, int x) {
   if (arr[right] <= x)
      return right;
   if (arr[left] > x)
      return left;
      int mid = (left + right)/2;
   if(arr[mid] <= x && arr[mid+1] > x)
      return mid;
   if(arr[mid] < x)
      return getCrossoverPoint(arr, mid+1, right, x);
      return getCrossoverPoint(arr, left, mid - 1, x);
}
void findKClosestNumbers(int arr[], int x, int k, int n) {
   int l = getCrossoverPoint(arr, 0, n-1, x);
   int r = l+1;
   int count = 0;
   if (arr[l] == x) l--;
      while (l >= 0 && r < n && count < k) {
         if (x - arr[l] < arr[r] - x)
            cout << arr[l--] << " ";
         else
            cout << arr[r++] << " ";
            count++;
      }
      while (count < k && l >= 0){
         cout << arr[l--] << " ";
         count++;
      }
      while (count < k && r < n){
         cout << arr[r++] << " ";
         count++;
      }
}
int main() {
   int arr[] ={12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56};
   int n = sizeof(arr)/sizeof(arr[0]);
   int x = 35, k = 5;
   findKClosestNumbers(arr, x, k, n);
}

Output

39 30 42 45 48

Updated on: 01-Nov-2019

86 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements