29 lines
770 B
JavaScript
29 lines
770 B
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;
|
|
// 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());
|