Data Structures19 sections · 729 units
Open in Course

Insert Operation

Bubble up

To insert an element:

1.1. Add it at the end of the array (next position in the complete tree).

2.2. "Bubble up": while it's smaller than its parent (in a min-heap), swap with parent.

3.3. Stop when heap property is restored.

function insert(heap, value)
    append value to heap
    i := length of heap - 1
    while i > 0 and heap[i] < heap[parent(i)]
        swap heap[i] and heap[parent(i)]
        i := parent(i)

At most O(logn)O(\log n) swaps, one per level.