Heap Insertion
To insert a new value into the heap, we perform the following algorithm:
-
We create a node containing the new value and insert it at the next available rightmost spot in the bottom level. Thus, this value becomes the heap’s last node.
-
Next, we compare this new node with its parent node.
-
If the new node is greater than its parent node, we swap the new node with the parent node.
-
We repeat Step 3, effectively moving the new node up through the heap, until the new node has a parent whose value is greater than it.
Let’s see this algorithm in action. Here’s what would happen if we were to insert a 40 into the heap.
Step 1: We add the 40 as the heap’s last node:
Note that doing the following would have been incorrect:
Placing the 40 as ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access