Created
September 25, 2019 03:50
-
-
Save ankitamasand/c9322b4614def52f05d3ef73590f01f4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
insert (node) { | |
/* Inserting the new node at the end of the heap array */ | |
this.heap.push(node) | |
/* Finding the correct position for the new node */ | |
if (this.heap.length > 1) { | |
let current = this.heap.length - 1 | |
/* Traversing up the parent node until the current node (current) is greater than the parent (current/2)*/ | |
while (current > 1 && this.heap[Math.floor(current/2)] > this.heap[current]) { | |
/* Swapping the two nodes by using the ES6 destructuring syntax*/ | |
[this.heap[Math.floor(current/2)], this.heap[current]] = [this.heap[current], this.heap[Math.floor(current/2)]] | |
current = Math.floor(current/2) | |
} | |
} | |
} |
👍 for swapping nodes using array destructuring
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Parent Node of current Node will be available at index
(current - 1) / 2
notcurrent / 2