Data Structures · Visualization
Heap Construction: Decrease Key
Heap Construction
Lowering a node's value (or raising it in a max-heap) can break the heap rule with its parent only — the subtree below is still fine. Time: O(log n) — at most the tree height. Space: O(1) extra.
Big-O: Bottom-up build O(n); decrease-key O(log n).
Heap Construction: Decrease Key
Heap ConstructionLowering a node's value (or raising it in a max-heap) can break the heap rule with its parent only — the subtree below is still fine. So instead of rebuilding, the node bubbles up: swap with the parent while the order is violated. Dijkstra's algorithm leans on exactly this operation.
How Decrease Key Works
- Change the value at index i in place.
- Compare with the parent at (i−1)/2.
- While the heap order is violated, swap upward.
- Stop at the root or when the parent is correctly ordered.
Decrease Key Worked Example
Input: Max-heap [10, 5, 3, 4, 1], raise index 4 from 1 to 9
- Set index 4 → 9: [10, 5, 3, 4, 9].
- Parent index 1 is 5 < 9 → swap → [10, 9, 3, 4, 5].
- Parent index 0 is 10 ≥ 9 → stop.
- Heap valid again after 1 bubble-up.
Output: Max-heap: [10, 9, 3, 4, 5]
Press ▶ Run to watch it step by step.
def decrease_key(a, i, v):
a[i] = v
while i > 0:
p = (i - 1) // 2
if a[p] >= a[i]: break
a[p], a[i] = a[i], a[p] # bubble up
i = p # O(log n)
# example: decrease 9 at index 4 on [10, 5, 3, 4, 1]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Decrease Key Time & Space Complexity
When to Use Decrease Key
- Dijkstra relaxing a shorter distance already in the queue
- Live leaderboards bumping a player's score upward
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.