51 lines
1.3 KiB
JavaScript
51 lines
1.3 KiB
JavaScript
|
// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/insert-an-element-into-a-max-heap
|
||
|
|
||
|
var MaxHeap = function () {
|
||
|
// Only change code below this line
|
||
|
this.heap = [];
|
||
|
|
||
|
this.insert = (item) => {
|
||
|
this.heap.push(item);
|
||
|
let me = this.heap.length - 1;
|
||
|
let parent = Math.trunc((me - 1) / 2);
|
||
|
while (parent != me && this.heap[parent] < this.heap[me]) {
|
||
|
const tmp = this.heap[parent];
|
||
|
this.heap[parent] = this.heap[me];
|
||
|
this.heap[me] = tmp;
|
||
|
me = parent;
|
||
|
parent = Math.trunc((me - 1) / 2);
|
||
|
}
|
||
|
};
|
||
|
|
||
|
this.print = () => this.heap;
|
||
|
|
||
|
this.remove = () => {
|
||
|
if (!this.heap.length) {
|
||
|
return;
|
||
|
}
|
||
|
const max = this.heap[0];
|
||
|
this.heap[0] = this.heap[this.heap.length - 1];
|
||
|
this.heap.pop();
|
||
|
let i = 0;
|
||
|
while (
|
||
|
this.heap[i] < this.heap[i * 2 + 1] ||
|
||
|
this.heap[i] < this.heap[i * 2 + 2]
|
||
|
) {
|
||
|
let swapWith = i * 2 + 1;
|
||
|
if (this.heap[swapWith] < this.heap[swapWith + 1]) swapWith++;
|
||
|
const tmp = this.heap[i];
|
||
|
this.heap[i] = this.heap[swapWith];
|
||
|
this.heap[swapWith] = tmp;
|
||
|
i = swapWith;
|
||
|
}
|
||
|
return max;
|
||
|
};
|
||
|
// Only change code above this line
|
||
|
};
|
||
|
|
||
|
const h = new MaxHeap();
|
||
|
for (let i = 0; i < 10; i++) {
|
||
|
h.insert(Math.trunc(Math.random() * 100));
|
||
|
}
|
||
|
console.log(h.print());
|