function findClosestElements(arr, k, x) {
const maxH = new MaxHeap();
const n = arr.length;
for (let i = 0; i < n; i++) {
if (arr[i] === x)
continue;
const diff = Math.abs(arr[i] - x);
maxH.insert({ diff: diff, value: -arr[i] });
if (maxH.size() > k)
maxH.extractMax();
}
const result = [];
while (!maxH.isEmpty()) {
const p = maxH.extractMax();
result.push(-p.value);
}
result.reverse();
return result;
}
class MaxHeap {
constructor() {
this.heap = [];
}
size() {
return this.heap.length;
}
isEmpty() {
return this.heap.length === 0;
}
insert(value) {
this.heap.push(value);
this.heapifyUp(this.heap.length - 1);
}
extractMax() {
if (this.isEmpty())
return null;
const max = this.heap[0];
const lastElement = this.heap.pop();
if (!this.isEmpty()) {
this.heap[0] = lastElement;
this.heapifyDown(0);
}
return max;
}
heapifyUp(index) {
const parentIndex = Math.floor((index - 1) / 2);
if (parentIndex >= 0 && this.heap[parentIndex].diff <
this.heap[index].diff) {
this.swap(parentIndex, index);
this.heapifyUp(parentIndex);
}
}
heapifyDown(index) {
const leftChildIndex = 2 * index + 1;
const rightChildIndex = 2 * index + 2;
let largestIndex = index;
if (leftChildIndex < this.heap.length &&
this.heap[leftChildIndex].diff >
this.heap[largestIndex].diff) {
largestIndex = leftChildIndex;
}
if (rightChildIndex < this.heap.length &&
this.heap[rightChildIndex].diff >
this.heap[largestIndex].diff) {
largestIndex = rightChildIndex;
}
if (largestIndex !== index) {
this.swap(largestIndex, index);
this.heapifyDown(largestIndex);
}
}
swap(index1, index2) {
[this.heap[index1], this.heap[index2]] =
[this.heap[index2], this.heap[index1]];
}
}
const arr = [12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56];
const k = 4;
const x = 35;
const res = findClosestElements(arr, k, x);
console.log(res);