Published
Edited
Dec 29, 2021
1 star
Insert cell
# Heap
Insert cell
{
const heap = new MaxHeap();

// push
heap.push(100);
heap.push(90);
heap.push(80);
heap.push(70);
heap.push(60);
// pop
heap.pop(); // 100
heap.pop(); // 90
heap.pop(); // 80
return heap.heap;
}
Insert cell
class MaxHeap {
constructor() {
this.heap = [null];
}

push(value) {
this.heap.push(value);
let currentIndex = this.heap.length - 1;
let parentIndex = Math.floor(currentIndex / 2);

while (parentIndex !== 0 && this.heap[parentIndex] < value) {
const temp = this.heap[parentIndex];
this.heap[parentIndex] = value;
this.heap[currentIndex] = temp;

currentIndex = parentIndex;
parentIndex = Math.floor(currentIndex / 2);
}
}

pop() {
const returnValue = this.heap[1];
if(this.heap.length === 2) {
return this.heap.pop();
}
this.heap[1] = this.heap.pop();

let currentIndex = 1;
let leftIndex = 2;
let rightIndex = 3;
while (
this.heap[currentIndex] < this.heap[leftIndex] ||
this.heap[currentIndex] < this.heap[rightIndex]
) {
if (this.heap[leftIndex] < this.heap[rightIndex]) {
const temp = this.heap[currentIndex];
this.heap[currentIndex] = this.heap[rightIndex];
this.heap[rightIndex] = temp;
currentIndex = rightIndex;
} else {
const temp = this.heap[currentIndex];
this.heap[currentIndex] = this.heap[leftIndex];
this.heap[leftIndex] = temp;
currentIndex = leftIndex;
}
leftIndex = currentIndex * 2;
rightIndex = currentIndex * 2 + 1;
}

return returnValue;
}
}

Insert cell
class MinHeap {
constructor() {
this.heap = [null];
}

push(value) {
this.heap.push(value);
let currentIndex = this.heap.length - 1;
let parentIndex = Math.floor(currentIndex / 2);

while (parentIndex !== 0 && this.heap[parentIndex] > value) {
const temp = this.heap[parentIndex];
this.heap[parentIndex] = value;
this.heap[currentIndex] = temp;

currentIndex = parentIndex;
parentIndex = Math.floor(currentIndex / 2);
}
}

pop() {
const returnValue = this.heap[1];
if(this.heap.length === 2) {
return this.heap.pop();
}
this.heap[1] = this.heap.pop();

let currentIndex = 1;
let leftIndex = 2;
let rightIndex = 3;
while (
this.heap[currentIndex] > this.heap[leftIndex] ||
this.heap[currentIndex] > this.heap[rightIndex]
) {
if (this.heap[leftIndex] > this.heap[rightIndex]) {
const temp = this.heap[currentIndex];
this.heap[currentIndex] = this.heap[rightIndex];
this.heap[rightIndex] = temp;
currentIndex = rightIndex;
} else {
const temp = this.heap[currentIndex];
this.heap[currentIndex] = this.heap[leftIndex];
this.heap[leftIndex] = temp;
currentIndex = leftIndex;
}
leftIndex = currentIndex * 2;
rightIndex = currentIndex * 2 + 1;
}

return returnValue;
}
}

Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more