Skip to content

Instantly share code, notes, and snippets.

@ankitamasand
Created September 25, 2019 03:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ankitamasand/c9322b4614def52f05d3ef73590f01f4 to your computer and use it in GitHub Desktop.
Save ankitamasand/c9322b4614def52f05d3ef73590f01f4 to your computer and use it in GitHub Desktop.
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)
}
}
}
@vpatel-gb
Copy link

Parent Node of current Node will be available at index (current - 1) / 2 not current / 2

@iplus26
Copy link

iplus26 commented Jul 25, 2021

👍 for swapping nodes using array destructuring

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment