Tracing Insert Operations #
Let's trace complete insertion sequences to build intuition for how bubble-up maintains the heap property.
Example 1: Building a Heap from Scratch #
Task: Insert the sequence: 50, 30, 70, 20, 60, 80, 10
Starting with empty heap:
Analysis of the Sequence #
Number of swaps per insertion:
| Value | Swaps | Reason |
|---|---|---|
| 50 | 0 | First element (root) |
| 30 | 0 | Smaller than parent |
| 70 | 1 | Larger than parent, bubbled to root |
| 20 | 0 | Smaller than parent |
| 60 | 1 | Larger than parent, stopped at grandparent |
| 80 | 2 | Largest so far, bubbled all the way to root |
| 10 | 0 | Smaller than parent |
Pattern observed: The number of swaps depends on:
- How large the inserted value is relative to its ancestors
- How far from the root it's inserted (tree height at that position)
Example 2: Worst-Case Insertion Scenario #
What's the worst case for a single insertion?
Inserting a value larger than all existing elements causes it to bubble all the way to the root.
Worst-case pattern: Inserting values in increasing order into an initially empty heap causes each element to bubble to the root.
Example - Inserting 10, 20, 30, 40, 50:
Example 3: Best-Case Insertion Scenario #
What's the best case?
Inserting a value smaller than its parent requires zero swaps.
Best-case pattern: Inserting the smallest value requires no swaps, regardless of tree size.
Visualizing Array vs Tree Operations #
Important concept: Each swap in the array corresponds to moving up one level in the tree.
Summary #
Key observations from tracing:
- Number of swaps ≤ height of tree - worst case is bubbling to the root
- Zero swaps is common - happens whenever inserted value is smaller than parent
- Each swap moves up exactly one level - corresponds to one level in the tree
- Complete binary tree property - ensures height is O(log n)
These traces demonstrate why insertion is O(log n) in the worst case—the maximum number of swaps equals the height of a complete binary tree with n nodes, which is ⌊log₂ n⌋.
On the next page, we'll see the remove() operation, which is more complex because it requires "bubble down" to restore the heap property.