Min-heap: insert and sift up

A heap is a complete binary tree stored in an array, where every parent is smaller than its children.

Time O(log n) per insertSpace O(1)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Add the new value at the end of the array, which is the next free leaf. While it is smaller than its parent, swap them. It climbs at most the height of the tree.

Code

public static void Push(List<int> heap, int value) {
    heap.Add(value);
    int i = heap.Count - 1;
    while (i > 0) {
        int parent = (i - 1) / 2;
        if (heap[parent] <= heap[i]) break;
        (heap[parent], heap[i]) = (heap[i], heap[parent]);
        i = parent;
    }
}
static void push(List<Integer> heap, int value) {
    heap.add(value);
    int i = heap.size() - 1;
    while (i > 0) {
        int parent = (i - 1) / 2;
        if (heap.get(parent) <= heap.get(i)) break;
        Collections.swap(heap, parent, i);
        i = parent;
    }
}
void push(vector<int>& heap, int value) {
    heap.push_back(value);
    int i = (int)heap.size() - 1;
    while (i > 0) {
        int parent = (i - 1) / 2;
        if (heap[parent] <= heap[i]) break;
        swap(heap[parent], heap[i]);
        i = parent;
    }
}
def push(heap: list[int], value: int) -> None:
    heap.append(value)
    i = len(heap) - 1
    while i > 0:
        parent = (i - 1) // 2
        if heap[parent] <= heap[i]: break
        heap[parent], heap[i] = heap[i], heap[parent]
        i = parent
    # heap order restored
# (heapq.heappush(heap, value) does exactly this)

Tips

In the .NET library

PriorityQueue<TElement, TPriority> (since .NET 6) is a min-heap. Enqueue(item, priority) does this sift-up for you.