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
using namespace std;
int getCrossoverPoint(int arr[], int left, int right, int x) {
   if (arr[right]  x)
      return left;
      int mid = (left + right)/2;
   if(arr[mid]  x)
      return mid;
   if(arr[mid] = 0 && r = 0){
         cout 

Output

39 30 42 45 48
Updated on: 2019-11-01T10:00:58+05:30

219 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements