From 0812d4b56a9f0695a0098f310c711d19d328cc95 Mon Sep 17 00:00:00 2001 From: Manish Date: Sat, 9 Sep 2023 17:15:12 +1000 Subject: [PATCH] Data Structures: Insert an Element into a Max Heap --- Data Structures/heapInsert.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Data Structures/heapInsert.js 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());