Data Structures · Visualization
Min-Heap: Insert
Min Heap
Inserting into a min-heap adds the new value at the next open spot at the end of the array, then 'bubbles it up': compares it with its parent and swaps if it's smaller, repeating until the value settles where the heap rule holds. Time: O(log n). Space: O(1) extra.
Big-O: Insert/extract O(log n); build O(n).
Min-Heap: Insert
Min HeapInserting into a min-heap adds the new value at the next open spot at the end of the array, then 'bubbles it up': compares it with its parent and swaps if it's smaller, repeating until the value settles where the heap rule holds.
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 smaller than its parent, swap them.
- Repeat the comparison/swap with the new parent, moving up the tree, until the value is bigger than its parent or it reaches the root.
Insert Worked Example
Input: Insert 5 into min-heap [10, 20, 15, 30, 25]
- Add 5 to the end: [10, 20, 15, 30, 25, 5]
- 5's parent is index 2 (value 15): 5 < 15, swap → [10, 20, 5, 30, 25, 15]
- 5's new parent is the root (10): 5 < 10, swap → [5, 20, 10, 30, 25, 15]
- 5 is now the root, stop
Output: [5, 20, 10, 30, 25, 15]
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 5 on [10, 20, 15, 30, 25]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 event with a timestamp into an event queue
- Streaming in cost values while always being able to access the current minimum
- 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.