class Heap {
constructor(compare) {
this.data = [];
this.compare = compare;
}
insert(value) {
this.data.push(value);
this.bubbleUp();
}
bubbleUp() {
let index = this.data.length - 1;
while (index > 0) {
let parentIndex = Math.floor((index - 1) / 2);
if (this.compare(this.data[index], this.data[parentIndex])) {
[this.data[index], this.data[parentIndex]] = [this.data[parentIndex], this.data[index]];
index = parentIndex; // move up to parent
} else {
break; // heap property satisfied
}
}
}
toString() {
return this.data.join(' -> ') + ' -> null';
}
}
// Min heap: smaller value has higher priority
const minHeap = new Heap((a, b) => a < b);
// Max heap: larger value has higher priority
const maxHeap = new Heap((a, b) => a > b);
const values = [5, 3, 9, 1, 7];
for (const val of values) {
minHeap.insert(val);
maxHeap.insert(val);
}
console.log('Min Heap final:', minHeap.toString());
console.log('Max Heap final:', maxHeap.toString());if (this.compare(this.data[index], this.data[parentIndex])) {
compare current node with parent to decide if swap needed
[this.data[index], this.data[parentIndex]] = [this.data[parentIndex], this.data[index]];
swap current node with parent to maintain heap property
index = parentIndex; // move up to parent
advance index upward to continue checking heap property
Min Heap final: 1 -> 3 -> 9 -> 5 -> 7 -> null
Max Heap final: 9 -> 7 -> 5 -> 1 -> 3 -> null