Last active
June 21, 2020 09:23
-
-
Save trykhov/edcf74ed74522077d5e37b5c337f31c3 to your computer and use it in GitHub Desktop.
Inserting nodes into a heap
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
// Assume the heap is represented as an array list: heap = [...] | |
// Assume we're dealing with a min-heap | |
function insertNode(node) { | |
// add the new node to the end of the list | |
heap.push(node); | |
// get the index of the new node | |
let lastIdx = heap.length - 1; | |
// find the parent of the new node | |
let parentIdx = lastIdx % 2 === 0 ? Math.floor(lastIdx / 2) - 1 : Math.floor(lastIdx / 2); | |
// this is for a min-heap: determine if the parent is larger than the child | |
if(heap[parentIdx] > heap[lastIdx]) { | |
// swap the parent with the child | |
let temp = heap[parentIdx]; | |
heap[parentIdx] = heap[lastIdx]; | |
heap[lastIdx] = temp; | |
} | |
// apply siftUp on the node | |
siftUp(parentIdx); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment