Data Structures · Visualization
Max-Heap: Insert
Max Heap
Inserting into a max-heap adds the new value at the very next open spot (the end of the array, keeping the tree complete), then 'bubbles it up': repeatedly compares it with its parent and swaps if it's larger, until it settles into a spot where the heap rule holds again. Time: O(log n). Space: O(1) extra.
Big-O: Insert/extract O(log n); build O(n).
Max-Heap: Insert
Max HeapInserting into a max-heap adds the new value at the very next open spot (the end of the array, keeping the tree complete), then 'bubbles it up': repeatedly compares it with its parent and swaps if it's larger, until it settles into a spot where the heap rule holds again.
How Insert Works
- Add the new value to the end of the array (the next open slot in the complete tree).
- Compare the new value with its parent.
- If the new value is greater than its parent, swap them.
- Repeat the comparison/swap with the new parent, moving up the tree, until the value is smaller than its parent or it reaches the root.
Insert Worked Example
Input: Insert 45 into max-heap [50, 30, 40, 10, 20]
- Add 45 to the end: [50, 30, 40, 10, 20, 45]
- 45's parent is index 2 (value 40): 45 > 40, swap → [50, 30, 45, 10, 20, 40]
- 45's new parent is the root (50): 45 < 50, stop
Output: [50, 30, 45, 10, 20, 40]
Press ▶ Run to watch it step by step.
def insert(heap, val):
heap.append(val)
i = len(heap) - 1
while i > 0 and heap[(i - 1) // 2] < heap[i]:
# bubble up while parent is smaller
heap[(i - 1) // 2], heap[i] = heap[i], heap[(i - 1) // 2]
i = (i - 1) // 2
# O(log n)
# example: insert 45 on [50, 30, 40, 10, 20]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.
Insert Time & Space Complexity
When to Use Insert
- Adding a new job with a priority level into a priority queue
- Streaming in values while always being able to access the current maximum
- Building a heap one element at a time
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.