class Heap {
constructor(i) {
this
.n = i;
this
.v =
new
Array(
this
.n);
}
}
function
left(i) {
return
2 * i + 1;
}
function
right(i) {
return
2 * i + 2;
}
function
findKthSmallest(h, k) {
const p =
new
MinHeap((a, b) => a[0] - b[0]);
p.add([h.v[0], 0]);
for
(let i = 0; i < k - 1; i++) {
const top = p.poll();
const j = top[1];
const l = left(j);
const r = right(j);
if
(l < h.n) {
p.add([h.v[l], l]);
}
if
(r < h.n) {
p.add([h.v[r], r]);
}
}
return
p.peek()[0];
}
class MinHeap {
constructor(comparator) {
this
.heap = [];
this
.comparator = comparator;
}
add(item) {
this
.heap.push(item);
this
.heapifyUp();
}
poll() {
if
(
this
.isEmpty()) {
throw
new
Error(
'The heap is empty.'
);
}
if
(
this
.heap.length === 1) {
return
this
.heap.pop();
}
const min =
this
.heap[0];
this
.heap[0] =
this
.heap.pop();
this
.heapifyDown();
return
min;
}
peek() {
if
(
this
.isEmpty()) {
throw
new
Error(
'The heap is empty.'
);
}
return
this
.heap[0];
}
isEmpty() {
return
this
.heap.length === 0;
}
size() {
return
this
.heap.length;
}
heapifyUp() {
let currentIndex =
this
.heap.length - 1;
while
(
this
.hasParent(currentIndex) &&
this
.compare(currentIndex,
this
.parentIndex(currentIndex)) < 0) {
this
.swap(currentIndex,
this
.parentIndex(currentIndex));
currentIndex =
this
.parentIndex(currentIndex);
}
}
heapifyDown() {
let currentIndex = 0;
while
(
this
.hasLeftChild(currentIndex)) {
let smallerChildIndex =
this
.leftChildIndex(currentIndex);
if
(
this
.hasRightChild(currentIndex) &&
this
.compare(
this
.leftChildIndex(currentIndex),
this
.rightChildIndex(currentIndex)) > 0) {
smallerChildIndex =
this
.rightChildIndex(currentIndex);
}
if
(
this
.compare(currentIndex, smallerChildIndex) < 0) {
break
;
}
else
{
this
.swap(currentIndex, smallerChildIndex);
}
currentIndex = smallerChildIndex;
}
}
hasParent(index) {
return
index > 0;
}
parentIndex(index) {
return
Math.floor((index - 1) / 2);
}
hasLeftChild(index) {
return
this
.leftChildIndex(index) <
this
.heap.length;
}
leftChildIndex(index) {
return
index * 2 + 1;
}
hasRightChild(index) {
return
this
.rightChildIndex(index) <
this
.heap.length;
}
rightChildIndex(index) {
return
index * 2 + 2;
}
compare(index1, index2) {
return
this
.comparator(
this
.heap[index1],
this
.heap[index2]);
}
swap(index1, index2) {
const temp =
this
.heap[index1];
this
.heap[index1] =
this
.heap[index2];
this
.heap[index2] = temp;
}
}
function
main() {
const h =
new
Heap(7);
h.v = [10, 50, 40, 75, 60, 65, 45];
const k = 4;
console.log(findKthSmallest(h, k));
}
main();