let heap = [];
function swap(index1, index2) {
[heap[index1], heap[index2]] = [heap[index2], heap[index1]]
}
function shiftup(index) {
let parentIndex = Math.floor((index - 1) / 2);
if (index != 0 && heap[parentIndex] < heap[index]) {
swap(parentIndex, index);
shiftup(parentIndex);
}
}
function shiftDown(index) {
let leftNodeIndex = (index + 1) * 2 - 1, rightNodeIndex = (index + 1) * 2
if (leftNodeIndex < heap.length && heap[leftNodeIndex] > heap[index]) {
swap(leftNodeIndex, index);
shiftDown(leftNodeIndex);
}
if (rightNodeIndex < heap.length && heap[rightNodeIndex] > heap[index]) {
swap(rightNodeIndex, index);
shiftDown(rightNodeIndex);
}
}
function insert(val) {
heap.push(val);
shiftup(heap.length - 1);
}
function remove() {
swap(0, heap.length - 1);
let temp = heap.pop();
shiftDown(0);
return temp;
}
insert(1);
insert(3);
insert(2);
insert(5);
console.log(heap)
console.log(remove());
console.log(heap)
insert(4);
insert(6);
console.log(remove());
console.log(heap)
insert(10)
console.log(heap)
console.log(remove())
console.log(remove())
console.log(remove())
console.log(remove())
console