Find k closest numbers in an unsorted array in C++


Consider we have an array A with few elements. The array is unsorted. 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 = [48, 50, 55, 30, 39, 35, 42, 45, 12, 16, 53, 22, 56] and X = 35, k = 4. The output will be 30, 39, 42, 45.

To solve this, we will use the heap data structure. The steps will be look like below −

  • Make one max-heap of differences with first k elements

  • For every element starting from k+1 th element, repeat these steps

    • Find difference between current element from x

    • If the difference is greater than the root of the heap, then ignore current element

    • Otherwise insert current element to the heap after removing the root.

  • Finally the heap will have k closest element.

Example

#include <iostream>
#include<queue>
using namespace std;
void findKClosestNumbers(int arr[], int n, int x, int k) {
   priority_queue<pair<int, int> > priorityQ;
   for (int i = 0; i < k; i++)
      priorityQ.push({ abs(arr[i] - x), i });
   for (int i = k; i < n; i++) {
      int diff = abs(arr[i] - x);
      if (diff > priorityQ.top().first)
         continue;
      priorityQ.pop();
      priorityQ.push({ diff, i });
   }
   while (priorityQ.empty() == false) {
      cout << arr[priorityQ.top().second] << " ";
      priorityQ.pop();
   }
}
int main() {
   int arr[] = {48, 50, 55, 30, 39, 35, 42, 45, 12, 16, 53, 22, 56};
   int x = 35, k = 5;
   int n = sizeof(arr) / sizeof(arr[0]);
   findKClosestNumbers(arr, n, x, k);
}

Output

45 42 30 39 35

Updated on: 01-Nov-2019

351 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements