diff --git a/Data Structures/heapInsert.js b/Data Structures/heapInsert.js new file mode 100644 index 0000000..7854ce6 --- /dev/null +++ b/Data Structures/heapInsert.js @@ -0,0 +1,28 @@ +// 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());