From 26410dcd97b1041e59c8cfa3351ec079339fad5d Mon Sep 17 00:00:00 2001 From: Manish Date: Sun, 10 Sep 2023 14:09:26 +1000 Subject: [PATCH] Data Structures: Remove an Element from a Max Heap --- Data Structures/heapRemove.js | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Data Structures/heapRemove.js diff --git a/Data Structures/heapRemove.js b/Data Structures/heapRemove.js new file mode 100644 index 0000000..61e7603 --- /dev/null +++ b/Data Structures/heapRemove.js @@ -0,0 +1,50 @@ +// 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());