Priority Queue and Binary Heap in C, C++, Java, Python and C#

How a binary heap backs a priority queue, why the standard libraries disagree about the top, and what the heap buys over a sorted array in practice.

A pale gray pyramid of nodes with a blue top node lifted above it, two green nodes directly beneath, and one empty socket at the right end of the bottom row.

A priority queue ignores arrival order. Every element carries a priority, and the next one served is the most important one still waiting. In the measured test below, 100,000 priorities pushed and popped through a binary heap took 14 ms. The same keys through a sorted array took 519 ms, 37 times longer, because every insert and every removal in the array shifts a large part of it. The heap buys its logarithm with one rule and two repairs, and the standard libraries disagree about whether the top is the largest or the smallest element.

This guide implements a min binary heap with stable handles in C, C++, Java, Python and C#, including the decrease-key operation that none of the standard priority queues offers. It then measures the heap against a sorted array, builds one in linear time, and compares the hand-written heap with std::priority_queue. It also shows where the libraries differ: std::priority_queue is a max-heap by default, while Python’s heapq, Java’s PriorityQueue and .NET’s PriorityQueue are min-heaps. Every program was built and tested on Ubuntu 24.04 under WSL2 and on Windows 11 with MSVC, Java, Python and .NET. All five languages print the same demo output byte for byte, and every output block below comes from a real run.

What Is a Priority Queue?

A priority queue is an abstract data type that stores elements with priorities and always returns the smallest or largest priority first, regardless of insertion order. A binary heap is the array-backed complete binary tree that implements it with O(log n) insert and remove and O(1) peek.

The difference from a FIFO queue is the ordering rule. A queue serves whoever arrived first, while a priority queue serves whoever matters most, and ties are broken by a rule the implementation documents or leaves unspecified. The abstract operations are small: insert an element with a priority, look at the top priority without removing it, remove the top, and sometimes lower an existing element’s priority. The last one, decrease-key, is the operation that the standard libraries leave out.

A heap is not the only possible implementation, and the alternatives explain the measured result. An unsorted array inserts in O(1) and finds the minimum in O(n). A sorted array finds it in O(1) and inserts in O(n), because the insertion shifts half the array on average. A binary heap keeps every operation at O(log n) by storing a complete binary tree in an array and repairing only one path after each change.

A balanced form of the binary search tree also gives O(log n) and supports the extra ordered operations, at a larger constant and a node per element. The array heap wins on constant factor and memory, which is why every standard library’s priority queue is an array-backed heap. C++, Java and Python use a binary heap, and .NET uses a four-ary one.

The structure appears wherever a greedy algorithm needs the next cheapest choice: Dijkstra’s algorithm, Prim’s algorithm, Huffman coding, event simulation, task scheduling and the “top k” queries heapq.nlargest exists for. The Heap Sort article uses the same array heap for sorting by removing the top repeatedly, while this article covers the queue itself and the operations around it. The Shortest Path article is where the decrease-key operation earns its keep, because Dijkstra lowers a known distance every time it finds a better edge.

A binary heap is an array with a tree inside it The same seven values at the same positions; only the way you walk them changes. array 0 1 1 4 2 3 3 7 4 9 5 8 6 5 parent (i – 1) / 2 left child 2i + 1 right child 2i + 2 1 0 4 1 3 2 7 3 9 4 8 5 5 6 The blue cell is index 1 and the blue node is the second level; its children are indexes 3 and 4, in green. Every parent is no greater than its children, so array position 0 holds the minimum.
Figure 1: The same seven priorities as an array and as a binary tree. The blue array cell at index 1 is the blue node, and its two children at indexes 3 and 4 are green: the parent and child formulas in the body are the arrows between the two views.

How This Was Measured

SettingValue
Date testedDecember 1, 2026
HardwareIntel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Windows 11 Education build 26300
Operating systemUbuntu 24.04.5 under WSL2, kernel 5.15.146.1-microsoft-standard-WSL2, glibc 2.39; Windows 11 for the MSVC, Java and .NET builds
CompilersGCC 13.3 and Clang 18.1.3 at -O2 and -O3 through CMake Release; MSVC 19.44 at /W4 /WX
Language runtimesOpenJDK 27.0.1.1 (the CI matrix covers 17, 21 and 25); CPython 3.14.6; .NET SDK 10.0.404
Heap against sorted array100,000 unique priorities, a shuffled permutation from a fixed xorshift64 seed, inserted and then extracted to empty in both structures
Build experiment1,000,000 unique priorities; repeated push against an array copy repaired bottom-up; build time only, heap property verified afterwards
Decrease-key experiment200,000 priorities with 100,000 lowered priorities, indexed change against the push-a-duplicate workaround
Standard-library benchmark1,000,000 inserts and extracts, median of 5 runs; 1,000,000 build-only std::make_heap against a push loop
What is timedThe data-structure calls only; key generation, allocation of the input array and verification are outside the timed regions
StatisticMedian of 5 for the C++ benchmark, single run for the quadratic C experiment, milliseconds
CheckThe two structures in each C experiment must agree on the extracted sequence or checksum; the min-heap C++ checksum must agree with the standard container

No CPU pinning or frequency scaling control was used, and the host runs other software, so timings are indicative for this machine and the ratios are the useful part. The sorted-array experiment is quadratic by construction at 100,000 priorities, so it and the heap side of it were run once. All numbers come from one machine and one WSL2 instance.

The Binary Heap: An Array That Behaves Like a Tree

A binary heap is a complete binary tree stored in an array with no pointers. The node at array position i has its left child at 2i + 1, its right child at 2i + 2, and its parent at (i - 1) / 2 for integer division. The tree is complete, so the array has no gaps and the height is always about log2 n.

The Binary Trees article covers the general tree vocabulary, and a heap is the special case where the tree is complete and the array is the whole representation. The heap property is one comparison per edge: in a min-heap every parent is no greater than its children, which puts the minimum at index 0.

Insertion appends the new priority at the end and repairs upward: while the new element is smaller than its parent, swap them and continue. Removal takes the root, moves the last element into index 0, and repairs downward: compare the element with its children, swap with the smaller child when one is smaller, and continue until it is smaller than both. Both repairs follow one path from leaf to root or root to leaf, so each costs O(log n).

Building from an unsorted array is faster than repeated insertion: repairing the bottom half from the last parent up to the root costs O(n) in total, because most nodes are near the bottom and travel short distances. That is the linear-time build the experiment measures.

OperationBinary heapSorted arrayUnsorted array
peekO(1)O(1)O(n)
insertO(log n)O(n)O(1)
remove topO(log n)O(1) stored descending, O(n) as measured hereO(n)
build from n elementsO(n)O(n log n)O(n)
decrease-key with a handleO(log n)O(n)O(n)

Two rules are easy to get wrong and account for most heap bugs: the child comparison in sift-down must consider both children, and the 0-based parent is (i - 1) / 2, not i / 2. Equal priorities are allowed but their relative order is unspecified, so a demo or test that depends on it is depending on the implementation, not the data type.

The heap in this article keeps one extra array. Every push returns a stable handle, and an index map records the current array position of each handle. Handles are never reused, so a handle whose element has gone stays dead instead of reaching some other element. Every swap updates both entries, which lets change_priority(handle, priority) sift the element in either direction without scanning the heap. That is the decrease-key operation, and it is what the standard containers below do not provide.

The Standard Libraries Do Not Agree on the Top

The same seven values can be a max-heap or a min-heap, and the standard libraries pick different defaults. The choice changes what peek and pop return and, more importantly, what a shortest-path implementation computes if the code assumes the wrong direction.

LanguageContainerDefault orderTo get the otherdecrease-key
Cnonenoneimplement itno
C++std::priority_queuemax-heap by defaultpass std::greater<T>no, push duplicates
JavaPriorityQueuemin-heap by defaultpass a reversed comparatorno, remove(Object) is O(n)
Pythonheapq functionsmin-heap by defaultthe _max functions (3.14 and later), or negate the valueno, push duplicates
C#PriorityQueue<TElement,TPriority> (four-ary heap)min-heap by defaultpass a custom IComparerno, Remove (.NET 9 and later) is O(n)

The C++ default is the odd one out in this list, and it is the mistake the fifth pitfall demonstrates: a program written as though std::priority_queue were a min-heap pops the largest priority first. The fix is one template argument, std::priority_queue<int, std::vector<int>, std::greater<>>, and it changes nothing else.

The missing decrease-key is the other shared gap. None of these containers can lower an existing element’s priority in place, because they do not expose a stable handle to an element. The standard workaround is to push a duplicate with the new priority and skip stale entries when they pop up, which the decrease-key experiment measures against the indexed implementation in this article. Python’s heapq adds convenience functions for the common cases: heappush, heappop, heapreplace (pop and push in one repair), heapify for the linear build, and nlargest/nsmallest for top-k queries. Python 3.14 added max-heap versions with a _max suffix, such as heappush_max and heapify_max.

Same seven values, two heap conventions Which one is at the root decides whether pop() returns the largest or the smallest. max-heap 93 55 71 42 17 23 8 std::priority_queue default min-heap 8 17 23 42 93 55 71 heapq, Java PriorityQueue, .NET PriorityQueue The values are identical. The heap property only fixes the direction: every parent is larger (max-heap) or smaller (min-heap) than its children, so the root is the extreme the comparator chooses. A priority queue for shortest paths needs the min-heap; the C++ default is the max-heap.
Figure 2: The same seven values as a max-heap and as a min-heap. The heap property fixes only the direction of every parent-child comparison, so the comparator decides whether the queue serves the largest or the smallest first. The standard libraries in this article do not agree on that direction.

Priority Queue Implementation in C

C has no priority queue in its standard library, so the implementation below is the whole data type. The heap is an array of entries, each holding a priority and an integer handle, plus a slots array that maps every handle to its index. The tree shape is implicit in the array indexes, so the structure has no pointers and no per-element allocation.

The Two Repairs

static void swap_slots(Heap *heap, size_t a, size_t b)
{
    int priority = heap->priorities[a];
    HeapHandle handle = heap->handles[a];
    heap->priorities[a] = heap->priorities[b];
    heap->handles[a] = heap->handles[b];
    heap->priorities[b] = priority;
    heap->handles[b] = handle;
    heap->slots[heap->handles[a]] = a;
    heap->slots[heap->handles[b]] = b;
}

/* Moves slot up until its parent is not larger. */
static void sift_up(Heap *heap, size_t slot)
{
    while (slot > 0) {
        size_t parent = (slot - 1) / 2;
        if (heap->priorities[parent] <= heap->priorities[slot])
            break;
        swap_slots(heap, parent, slot);
        slot = parent;
    }
}

/* Moves slot down until it is not larger than either child. */
static void sift_down(Heap *heap, size_t slot)
{
    for (;;) {
        size_t left = 2 * slot + 1;
        size_t right = left + 1;
        size_t smallest = slot;
        if (left < heap->size &&
            heap->priorities[left] < heap->priorities[smallest])
            smallest = left;
        if (right < heap->size &&
            heap->priorities[right] < heap->priorities[smallest])
            smallest = right;
        if (smallest == slot)
            break;
        swap_slots(heap, slot, smallest);
        slot = smallest;
    }
}

/* Inserts a priority and returns its handle, or HEAP_HANDLE_NONE when the
 * heap could not grow. */
HeapHandle heap_push(Heap *heap, int priority)
{
    HeapHandle handle;
    if (heap->next_handle == HEAP_HANDLE_NONE)
        return HEAP_HANDLE_NONE;            /* all handles issued */
    if (heap->size == heap->capacity && !grow_heap(heap))
        return HEAP_HANDLE_NONE;
    if (heap->next_handle == heap->slot_capacity && !grow_slots(heap))
        return HEAP_HANDLE_NONE;
    handle = heap->next_handle;
    heap->next_handle = handle + 1;
    heap->priorities[heap->size] = priority;
    heap->handles[heap->size] = handle;
    heap->slots[handle] = heap->size;
    heap->size++;
    sift_up(heap, heap->size - 1);
    return handle;
}
/* Removes the smallest priority. Returns false when the heap is empty; the
 * handle of the removed element stops being valid. */
bool heap_pop(Heap *heap, int *out)
{
    HeapHandle last;
    if (heap->size == 0)
        return false;
    *out = heap->priorities[0];
    heap->slots[heap->handles[0]] = HEAP_SLOT_NONE;
    heap->size--;
    if (heap->size > 0) {
        last = heap->handles[heap->size];
        heap->priorities[0] = heap->priorities[heap->size];
        heap->handles[0] = last;
        heap->slots[last] = 0;
        sift_down(heap, 0);
    }
    return true;
}

/* Moves the element behind handle to priority, in either direction. Returns
 * false for a dead or never-issued handle, leaving the heap unchanged. */
bool heap_change_priority(Heap *heap, HeapHandle handle, int priority)
{
    size_t slot;
    int old;
    if (handle >= heap->next_handle)
        return false;
    slot = heap->slots[handle];
    if (slot == HEAP_SLOT_NONE)
        return false;
    old = heap->priorities[slot];
    if (priority == old)
        return true;
    heap->priorities[slot] = priority;
    if (priority < old)
        sift_up(heap, slot);
    else
        sift_down(heap, slot);
    return true;
}

sift_up and sift_down are the only two ways the heap changes shape. Every swap goes through swap_slots, which updates both entries of the index map, so the map stays correct through insertions, removals and priority changes. heap_push appends and sifts up. heap_pop takes the root, moves the last entry to index 0 if any remain, and sifts down. heap_change_priority looks the handle up in the index map, writes the new priority, and sifts in the direction the priority moved. heap_build numbers its elements after every handle issued so far, so a handle from before the build is rejected rather than silently pointing at a new element.

The Demo

The demo pushes seven priorities, prints the ordering after a full drain, then exercises a priority change and the linear-time build. The handle for 61 comes from the push call itself, so the change is one array lookup rather than a scan.

Output:

binary heap priority queue, smaller number is higher priority
push 42, 17, 93, 8, 55, 23, 71 -> size 7, peek 8
pop until empty: 8 17 23 42 55 71 93 -> size 0
push 4, 61, 19, 88 -> peek 4
change 61 to 2 -> peek 2, size 4
pop until empty: 2 4 19 88 -> size 0
heapify 9, 3, 7, 1, 8, 2 -> peek 1, size 6
pop until empty: 1 2 3 7 8 9 -> size 0

Priority Queue Implementation in C++

The C++ version is the same design as a class template: PriorityQueue<T, Compare = std::less<T>> stores priorities in a std::vector, keeps a parallel handle vector and an index map, and returns stable handles that are never reused. std::optional reports absence from peek. The comparator is a template parameter, so the same class is a min-heap by default and a max-heap with std::greater<T>, and the demo’s ordering does not depend on which one the standard library chose.

    bool change_priority(handle_type handle, T priority)
    {
        if (handle >= positions_.size() || positions_[handle] == npos)
            return false;
        const size_type position = positions_[handle];
        priorities_[position] = std::move(priority);
        if (position > 0 &&
            comp_(priorities_[position], priorities_[(position - 1) / 2]))
            sift_up(position);
        else
            sift_down(position);
        return true;
    }

    // Builds the heap from priorities in O(n) by repairing down from the last
    // parent. The queue's previous contents are discarded and their handles go
    // dead. priorities[i] gets the handle first + i, where first is the value
    // returned, so the new handles never collide with the old ones.
    handle_type heapify(const std::vector<T>& priorities)
    {
        for (const handle_type handle : handles_)
            positions_[handle] = npos;
        const handle_type first = positions_.size();
        priorities_ = priorities;
        handles_.resize(priorities_.size());
        positions_.resize(first + priorities_.size(), npos);
        for (size_type position = 0; position < handles_.size(); ++position) {
            handles_[position] = first + position;
            positions_[first + position] = position;
        }
        for (size_type position = priorities_.size() / 2; position > 0;) {
            --position;
            sift_down(position);
        }
        return first;
    }
    void sift_up(size_type position)
    {
        T priority = std::move(priorities_[position]);
        const handle_type handle = handles_[position];
        while (position > 0) {
            const size_type parent = (position - 1) / 2;
            if (!comp_(priority, priorities_[parent]))
                break;
            priorities_[position] = std::move(priorities_[parent]);
            handles_[position] = handles_[parent];
            positions_[handles_[position]] = position;
            position = parent;
        }
        priorities_[position] = std::move(priority);
        handles_[position] = handle;
        positions_[handle] = position;
    }

    // Moves the element at position toward the leaves, always through the
    // higher-priority child.
    void sift_down(size_type position)
    {
        T priority = std::move(priorities_[position]);
        const handle_type handle = handles_[position];
        for (;;) {
            size_type child = position * 2 + 1;
            if (child >= priorities_.size())
                break;
            if (child + 1 < priorities_.size() &&
                comp_(priorities_[child + 1], priorities_[child]))
                ++child;
            if (!comp_(priorities_[child], priority))
                break;
            priorities_[position] = std::move(priorities_[child]);
            handles_[position] = handles_[child];
            positions_[handles_[position]] = position;
            position = child;
        }
        priorities_[position] = std::move(priority);
        handles_[position] = handle;
        positions_[handle] = position;
    }

The standard alternative is std::priority_queue from <queue>, which is a max-heap by default and a container adapter over std::vector or std::deque. It has push, pop, top, size and empty, no iteration and no handle to an element. Use it when the workload is push and pop only. Use the class above when a priority must change in place, or std::make_heap directly when the data already lives in an array. The cppreference page lists the adapter’s full interface, including the comparator position that turns it into a min-heap.

Custom Heap Against std::priority_queue

int main()
{
    const std::vector<int> priorities = shuffled_priorities(kCount);

    const Result custom_min = median_run([&priorities] {
        return run_custom_min(priorities);
    });
    const Result std_min = median_run([&priorities] {
        return run_std_min(priorities);
    });
    const Result std_max = median_run([&priorities] {
        return run_std_max(priorities);
    });
    if (custom_min.checksum != std_min.checksum) {
        std::fprintf(stderr, "the two min-heaps extracted different checksums\n");
        return EXIT_FAILURE;
    }

    const double make_heap_ms = median_time([&priorities] {
        return run_make_heap(priorities);
    });
    const double push_loop_ms = median_time([&priorities] {
        return run_push_loop(priorities);
    });

    std::printf("1,000,000 inserts + extracts, median of 5 runs (ms)\n");
    std::printf("custom min-heap              %.1f\n", custom_min.ms);
    std::printf("std::priority_queue min      %.1f\n", std_min.ms);
    std::printf("std::priority_queue max      %.1f\n", std_max.ms);
    std::printf("1,000,000 build only, median of 5 runs (ms)\n");
    std::printf("std::make_heap               %.1f\n", make_heap_ms);
    std::printf("push loop                    %.1f\n", push_loop_ms);
    std::printf("checksum min: %llu\n",
                static_cast<unsigned long long>(custom_min.checksum));
    std::printf("checksum max: %llu\n",
                static_cast<unsigned long long>(std_max.checksum));
    return EXIT_SUCCESS;
}

Output:

1,000,000 inserts + extracts, median of 5 runs (ms)
custom min-heap              280.9
std::priority_queue min      117.0
std::priority_queue max      114.0
1,000,000 build only, median of 5 runs (ms)
std::make_heap               7.6
push loop                    10.0
checksum min: 4646587707647723520
checksum max: 12966943144614045184

On a million inserts and extracts the standard container took 117.0 ms against 280.9 ms for the custom indexed heap, about 2.4 times faster. The custom heap maintains a second array of handles and a position map and updates them on every move, while std::priority_queue moves only the priorities. The default max variant took 114.0 ms, so the comparator direction costs nothing measurable. The build-only pair shows the other side: std::make_heap built the million priorities in 7.6 ms against 10.0 ms for pushing them one at a time, about a quarter less time. The C experiment below points the same way with a smaller gap, 19 ms against 21 ms.

The standard container is the right default for push and pop. The custom heap buys the index map that makes change_priority possible, and this benchmark is the price of that map.

Priority Queue Implementation in Java, Python and C#

The three implementations follow the C design: an array-backed min-heap with stable handles and an index map, plus a linear-time build. Their standard libraries all provide a min-heap priority queue by default, so the library sections below focus on the API differences and on the operations the library leaves out.

Java

    public boolean changePriority(int handle, int priority) {
        if (handle < 0 || handle >= slotOfHandle.length) {
            return false;
        }
        int slot = slotOfHandle[handle];
        if (slot < 0) {
            return false;
        }
        int previous = priorities[slot];
        priorities[slot] = priority;
        if (priority < previous) {
            siftUp(slot);
        } else if (priority > previous) {
            siftDown(slot);
        }
        return true;
    }

    /** Number of stored priorities. */
    public int size() {
        return size;
    }

    /** True when nothing is stored. */
    public boolean isEmpty() {
        return size == 0;
    }

    /** Moves a smaller priority up until the parent is not larger. */
    private void siftUp(int slot) {
        while (slot > 0) {
            int parent = (slot - 1) / 2;
            if (priorities[slot] >= priorities[parent]) {
                return;
            }
            swap(slot, parent);
            slot = parent;
        }
    }

    /** Moves a larger priority down until neither child is smaller. */
    private void siftDown(int slot) {
        while (true) {
            int left = 2 * slot + 1;
            if (left >= size) {
                return;
            }
            int smallest = left;
            int right = left + 1;
            if (right < size && priorities[right] < priorities[left]) {
                smallest = right;
            }
            if (priorities[smallest] >= priorities[slot]) {
                return;
            }
            swap(slot, smallest);
            slot = smallest;
        }
    }

    /** Swaps two heap slots and keeps the index map pointing at them. */
    private void swap(int first, int second) {
        int priority = priorities[first];
        priorities[first] = priorities[second];
        priorities[second] = priority;
        int handle = handles[first];
        handles[first] = handles[second];
        handles[second] = handle;
        slotOfHandle[handles[first]] = first;
        slotOfHandle[handles[second]] = second;
    }

MinHeap is a class of int priorities. add returns the handle, peek and poll throw IllegalStateException when empty, and changePriority takes the handle. The tests compare it against a sorted ArrayList model and check the array layout, the index map and the heap property.

The library container is PriorityQueue, a min-heap with offer/add, peek, poll and remove, and a comparator constructor that flips it to a max-heap. It has no decrease-key, and remove(Object) is O(n) because it searches. PriorityQueue also rejects null elements.

Python

    def change_priority(self, handle: int, priority: P) -> bool:
        """Move an existing element to a new priority.

        Raises no exception for an unknown handle: a popped handle is invalid
        input, so the call reports False and leaves the heap unchanged.  The
        return value reports whether the handle was live.
        """
        index = self._positions.get(handle)
        if index is None:
            return False
        entry = self._entries[index]
        if priority < entry.priority:
            entry.priority = priority
            self._sift_up(index)
        elif entry.priority < priority:
            entry.priority = priority
            self._sift_down(index)
        return True
    def _swap(self, first: int, second: int) -> None:
        """Exchange two entries and keep their positions in the map in step."""
        entries = self._entries
        entries[first], entries[second] = entries[second], entries[first]
        self._positions[entries[first].handle] = first
        self._positions[entries[second].handle] = second

    def _sift_up(self, index: int) -> None:
        """Move the entry at index up while it is smaller than its parent."""
        entries = self._entries
        while index > 0:
            parent = (index - 1) // 2
            if not entries[index].priority < entries[parent].priority:
                return
            self._swap(index, parent)
            index = parent

    def _sift_down(self, index: int) -> None:
        """Move the entry at index down while a child is smaller than it."""
        entries = self._entries
        size = len(entries)
        while True:
            child = 2 * index + 1
            if child >= size:
                return
            right = child + 1
            if right < size and entries[right].priority < entries[child].priority:
                child = right
            if not entries[child].priority < entries[index].priority:
                return
            self._swap(index, child)
            index = child

The Python class keeps a list of entries, each holding a priority and its handle, a handle-to-position map and an int counter. peek and pop raise IndexError when the heap is empty, and change_priority moves the element in either direction.

Python’s standard library provides heapq: functions over a plain list, not a class. The core functions are heappush, heappop, heappushpop, heapreplace and heapify, plus merge, nlargest and nsmallest. The plain functions build a min-heap, and Python 3.14 added _max versions for a max-heap, which older code gets by negating the values. The module is implemented in C and runs the same kind of sift repairs as the class above. What it does not have is a handle, so a priority change means pushing a duplicate.

C#

    public bool ChangePriority(int handle, int priority)
    {
        if (handle < 0 || handle >= _handleCount)
            return false;

        int slot = _slot[handle];
        if (slot < 0)
            return false;

        int old = _priority[handle];
        if (priority == old)
            return true;

        _priority[handle] = priority;
        if (priority < old)
            SiftUp(slot);
        else
            SiftDown(slot);
        return true;
    }
    private void SiftUp(int slot)
    {
        while (slot > 0)
        {
            int parent = (slot - 1) / 2;
            if (_priority[_heap[slot]] >= _priority[_heap[parent]])
                return;

            Swap(slot, parent);
            slot = parent;
        }
    }

    private void SiftDown(int slot)
    {
        while (true)
        {
            int left = (2 * slot) + 1;
            if (left >= _count)
                return;

            int smallest = left;
            int right = left + 1;
            if (right < _count && _priority[_heap[right]] < _priority[_heap[left]])
                smallest = right;

            if (_priority[_heap[slot]] <= _priority[_heap[smallest]])
                return;

            Swap(slot, smallest);
            slot = smallest;
        }
    }

    private void Swap(int a, int b)
    {
        int temp = _heap[a];
        _heap[a] = _heap[b];
        _heap[b] = temp;
        _slot[_heap[a]] = a;
        _slot[_heap[b]] = b;
    }

The C# class follows the same shape with Add, Peek, Pop, ChangePriority, Count and Heapify. Empty Peek and Pop throw InvalidOperationException, and the tests compare against a sorted-list model.

.NET 6 and later have PriorityQueue<TElement,TPriority>, an array-backed four-ary min-heap with Enqueue, Dequeue, Peek and a custom IComparer for the opposite order. It also lacks decrease-key and a stable handle. Remove, added in .NET 9, scans the whole heap in O(n), so the practical workaround is the same push-a-duplicate pattern.

Heap Against Sorted Array: The Measured Cost

The first experiment compares the heap with the simplest priority queue a beginner writes: an array kept in ascending order, where “insert” is a binary search plus a memmove, and “remove the minimum” shifts the whole array left. Storing the array in descending order would make the removal O(1), but insertion would still shift half the array on average. Both structures receive the same 100,000 priorities and must extract them in ascending order.

static bool run_heap(const int *priorities, size_t count, long *insert_ms,
                     long *extract_ms, unsigned long long *sum)
{
    Heap heap;
    double started = 0.0;
    size_t i;
    int previous = 0;
    bool ascending = true;

    heap_init(&heap);
    *sum = FNV_OFFSET;
    started = now_ms();
    for (i = 0; i < count; ++i) {
        if (heap_push(&heap, priorities[i]) == HEAP_HANDLE_NONE) {
            heap_free(&heap);
            return false;
        }
    }
    *insert_ms = elapsed_ms(started);
    started = now_ms();
    for (i = 0; i < count; ++i) {
        int value = 0;
        if (!heap_pop(&heap, &value)) {
            ascending = false;
            break;
        }
        if (i == 0) {
            if (value != 0)
                ascending = false;
        } else if (value <= previous) {
            ascending = false;
        }
        previous = value;
        *sum = checksum_add(*sum, value);
    }
    *extract_ms = elapsed_ms(started);
    if (heap_size(&heap) != 0)
        ascending = false;
    heap_free(&heap);
    return ascending && previous == (int)count - 1;
}

/* The sorted-array baseline: keep an ascending array, binary search plus a
 * memmove in, a memmove from the front out. */
static bool run_sorted_array(const int *priorities, size_t count,
                             long *insert_ms, long *extract_ms,
                             unsigned long long *sum)
{
    int *values = malloc(count * sizeof *values);
    size_t size = 0;
    size_t i;
    double started = 0.0;
    int previous = 0;
    bool ascending = true;

    if (values == NULL)
        return false;
    *sum = FNV_OFFSET;
    started = now_ms();
    for (i = 0; i < count; ++i) {
        size_t lo = 0;
        size_t hi = size;
        while (lo < hi) {
            size_t mid = lo + (hi - lo) / 2;
            if (values[mid] < priorities[i])
                lo = mid + 1;
            else
                hi = mid;
        }
        memmove(&values[lo + 1], &values[lo], (size - lo) * sizeof *values);
        values[lo] = priorities[i];
        size++;
    }
    *insert_ms = elapsed_ms(started);
    started = now_ms();
    for (i = 0; i < count; ++i) {
        int value = values[0];
        if (i == 0) {
            if (value != 0)
                ascending = false;
        } else if (value <= previous) {
            ascending = false;
        }
        previous = value;
        *sum = checksum_add(*sum, value);
        memmove(&values[0], &values[1], (size - 1) * sizeof *values);
        size--;
    }
    *extract_ms = elapsed_ms(started);
    free(values);
    return ascending && size == 0 && previous == (int)count - 1;
}

Output:

100,000 priorities, insert all then extract until empty
structure      insert_ms  extract_ms  total_ms  checksum
binary heap            2          12        14  2601778742065945539
sorted array         154         365       519  2601778742065945539

The phases are as different as the totals. The heap inserted 100,000 priorities in 2 ms and extracted them in 12 ms. Insertion sifts up a short distance, and extraction pays the root-to-leaf repair for every element. The sorted array took 154 ms to insert, a binary search plus a memmove of half the array on average, and 365 ms to extract, a memmove of the remaining array for every pop. That is 519 ms in total, 37 times the heap.

Both structures produced the same FNV-1a checksum over the extracted priorities, so the comparison is on identical work. The ratio is the useful number. Each array operation moves a share of a larger array as n grows, while the heap’s path grows only logarithmically, so the gap widens with n.

Inserting then extracting 100,000 priorities Milliseconds, logarithmic scale. The sorted array loses both phases. binary heap: insert 2.0 binary heap: extract 12.0 sorted array: insert 154.0 sorted array: extract 365.0 1 10 100 1000 milliseconds (log scale) Total: heap 14.0 ms against sorted array 519.0 ms, 37 times slower. Same keys, same verification of the extracted order; only the data structure differs.
Figure 3: Insert then extract 100,000 priorities, binary heap against a sorted array, on a logarithmic millisecond scale. The heap pays a logarithm per operation, while the sorted array pays a memmove on every insert and every extract.

Building a Heap in Linear Time

A heap can be built faster than by pushing one element at a time. Copying an unsorted array and repairing every parent from the last one up to the root costs O(n) in total, because the bottom rows hold most of the elements and each one moves only a short distance. The experiment builds 1,000,000 priorities both ways and checks the heap property afterwards.

int main(void)
{
    int *priorities = malloc((size_t)PRIORITY_COUNT * sizeof *priorities);
    Heap heap;
    long push_ms = 0;
    long heapify_ms = 0;
    bool push_valid = false;
    bool heapify_valid = false;
    bool peek_valid = true;
    int push_peek = 0;
    int heapify_peek = 0;
    double started = 0.0;
    size_t i;

    if (priorities == NULL) {
        fputs("out of memory\n", stderr);
        return EXIT_FAILURE;
    }
    for (i = 0; i < (size_t)PRIORITY_COUNT; ++i)
        priorities[i] = (int)i;
    rng_state = SEED_SHUFFLE;
    shuffle(priorities, (size_t)PRIORITY_COUNT);

    printf("1,000,000 priorities, build only\n");
    printf("%-15s %8s  %5s  %s\n", "method", "build_ms", "valid", "peek");

    /* Method A: one push at a time into an empty heap. */
    heap_init(&heap);
    started = now_ms();
    for (i = 0; i < (size_t)PRIORITY_COUNT; ++i) {
        if (heap_push(&heap, priorities[i]) == HEAP_HANDLE_NONE) {
            fputs("push failed\n", stderr);
            heap_free(&heap);
            free(priorities);
            return EXIT_FAILURE;
        }
    }
    push_ms = elapsed_ms(started);
    push_valid = heap_property_holds(&heap, (size_t)PRIORITY_COUNT);
    if (!heap_peek(&heap, &push_peek))
        peek_valid = false;
    printf("%-15s %8ld  %5s  %d\n", "push one by one", push_ms,
           push_valid ? "true" : "false", push_peek);
    heap_free(&heap);

    /* Method B: copy the array and repair it bottom-up. */
    heap_init(&heap);
    started = now_ms();
    if (!heap_build(&heap, priorities, (size_t)PRIORITY_COUNT)) {
        fputs("heapify failed\n", stderr);
        free(priorities);
        return EXIT_FAILURE;
    }
    heapify_ms = elapsed_ms(started);
    heapify_valid = heap_property_holds(&heap, (size_t)PRIORITY_COUNT);
    if (!heap_peek(&heap, &heapify_peek))
        peek_valid = false;
    printf("%-15s %8ld  %5s  %d\n", "bottom-up build", heapify_ms,
           heapify_valid ? "true" : "false", heapify_peek);
    heap_free(&heap);

    free(priorities);
    if (!push_valid || !heapify_valid || !peek_valid ||
        push_peek != 0 || heapify_peek != 0) {
        fputs("a built heap is not a valid min heap\n", stderr);
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

Output:

1,000,000 priorities, build only
method          build_ms  valid  peek
push one by one       21   true  0
bottom-up build       19   true  0

Build-only time barely separates the two methods at one million priorities: 21 ms for a million pushes and 19 ms for bottom-up heapify, a 10% difference. The C++ containers favored the linear build by more, 7.6 ms against 10.0 ms.

The textbook says the linear build does asymptotically less work, and it does. A million insertions can cost O(n log n) in the worst case, such as input in descending order, while bottom-up repairs every parent once for O(n) work in total. The measured gap is small because the input is a random permutation, and a newly inserted random element usually rises only a level or two before it stops. The linear build’s advantage is clearest in the worst case and in the comparison count rather than in wall-clock time at this size. Both heaps passed the property check, and both put the same minimum at the root.

Decrease-Key Without a Library

Dijkstra’s algorithm needs to lower the priority of an element already in the queue. No standard priority queue can do that in place, because none of them exposes a stable handle. The experiment compares the two ways out: the indexed implementation from this article, which looks the handle up and sifts it, and the standard workaround, which pushes a duplicate and skips the stale entry when it surfaces.

static void entry_swap(EntryHeap *heap, size_t a, size_t b)
{
    Entry swap = heap->entries[a];
    heap->entries[a] = heap->entries[b];
    heap->entries[b] = swap;
}

static void entry_sift_up(EntryHeap *heap, size_t slot)
{
    while (slot > 0) {
        size_t parent = (slot - 1) / 2;
        if (heap->entries[parent].priority <= heap->entries[slot].priority)
            break;
        entry_swap(heap, parent, slot);
        slot = parent;
    }
}

static void entry_sift_down(EntryHeap *heap, size_t slot)
{
    for (;;) {
        size_t left = 2 * slot + 1;
        size_t right = left + 1;
        size_t smallest = slot;
        if (left < heap->size &&
            heap->entries[left].priority < heap->entries[smallest].priority)
            smallest = left;
        if (right < heap->size &&
            heap->entries[right].priority < heap->entries[smallest].priority)
            smallest = right;
        if (smallest == slot)
            break;
        entry_swap(heap, slot, smallest);
        slot = smallest;
    }
}

static bool entry_push(EntryHeap *heap, int priority, size_t handle)
{
    if (heap->size == heap->capacity)
        return false;
    heap->entries[heap->size].priority = priority;
    heap->entries[heap->size].handle = handle;
    heap->size++;
    entry_sift_up(heap, heap->size - 1);
    return true;
}

static Entry entry_pop(EntryHeap *heap)
{
    Entry top = heap->entries[0];
    heap->size--;
    if (heap->size > 0) {
        heap->entries[0] = heap->entries[heap->size];
        entry_sift_down(heap, 0);
    }
    return top;
}

Output:

200,000 priorities, 100,000 decreases
method                  change_ms  pop_ms  heap_entries
indexed change_priority         3      26  200000
reinsert duplicates             2      37  300000
checksum: 3324451326809841748

The two methods end with the same effective priorities but not the same cost. Indexed change_priority spent 3 ms on the 100,000 changes and 26 ms draining the heap, 29 ms in total, and it held 200,000 entries. Reinsert duplicates spent 2 ms changing, because a push is cheap and the stale entry stays where it is. It then spent 37 ms draining a 300,000-entry heap that carried 100,000 stale entries, 39 ms in total.

The indexed version pays for updating the index map on every swap, while the duplicate version pays later in memory and pop time. At this size the indexed method took about a quarter less time (29 ms against 39 ms). Every extra change adds one more stale entry to the duplicate heap, so the indexed heap suits workloads with many changes or a tight memory budget.

Five Ways a Priority Queue Passes a Quick Test and Still Fails

Each of these programs compiles cleanly with -Wall -Wextra -pedantic and prints something plausible until the line below it. The first four live in the C repository’s pitfalls/ directory and the fifth in the C++ repository’s; the workflows re-run each and assert the line that shows the bug.

1. Sift-Down That Only Looks Left

static void sift_down(Heap *heap, size_t slot)
{
    for (;;) {
        size_t left = 2 * slot + 1;
        if (left >= heap->size ||
            heap->priorities[left] >= heap->priorities[slot])
            break;
        swap(heap, slot, left);
        slot = left;
    }
}

static void push(Heap *heap, int priority)
{
    heap->priorities[heap->size] = priority;
    heap->size++;
    sift_up(heap, heap->size - 1);
}

static bool pop(Heap *heap, int *out)
{
    if (heap->size == 0)
        return false;
    *out = heap->priorities[0];
    heap->size--;
    if (heap->size > 0) {
        heap->priorities[0] = heap->priorities[heap->size];
        sift_down(heap, 0);
    }
    return true;
}

Output:

sift_down_left_only: sift-down compares only the left child
push 1, 5, 2, 9, 8, 7 -> size 6, peek 1
pop order: 1 5 7 8 2 9, expected 1 2 5 7 8 9

The buggy sift-down compares the parent with its left child only. Every push succeeds and peek is correct, then the pop order breaks: 1 5 7 8 2 9 instead of 1 2 5 7 8 9, because the right child 2 sits under a larger parent and is never promoted. The fix is the smaller-of-two-children comparison inside sift_down, and the test has to check the whole drain rather than the top or the size.

2. The Parent of Index i Is Not i / 2

static void sift_up(Heap *heap, size_t slot)
{
    while (slot > 0) {
        size_t parent = slot / 2;
        if (heap->priorities[parent] <= heap->priorities[slot])
            break;
        swap(heap, parent, slot);
        slot = parent;
    }
}

Output:

zero_based_parent: parent computed as i / 2 on a 0-based array
push 2, 3, 8, 1, 9, 10, 4, 6, 7, 5 -> size 10, peek 1
pop 4: the root holds 5 while the minimum is 4
pop order: 1 2 3 5 4 6 7 8 9 10, expected 1 2 3 4 5 6 7 8 9 10

On a 0-based array the parent of slot i is (i – 1) / 2, not i / 2. When 4 is pushed into slot 6, the buggy code compares it with slot 3 (value 3) instead of its true parent, slot 2 (value 8 at that moment). So 4 stays below a larger element and the heap property breaks below an unchanged root. Pushes still succeed and the size is right. The damage shows on removal: pop 4 finds 5 at the root while the minimum 4 is still deeper. The fix is one subtraction, and the test must check the popped order, not just peek.

3. A Build That Starts One Index Too High

static void sift_down(int priorities[], size_t size, size_t slot)
{
    for (;;) {
        size_t left = 2 * slot + 1;
        size_t right = left + 1;
        size_t smallest = slot;
        if (left < size && priorities[left] < priorities[smallest])
            smallest = left;
        if (right < size && priorities[right] < priorities[smallest])
            smallest = right;
        if (smallest == slot)
            break;
        swap(priorities, slot, smallest);
        slot = smallest;
    }
}

/* The bug: the last internal slot is n / 2 - 1, so starting at n / 2 skips
 * the root and the root is never repaired. */
static void heapify(int priorities[], size_t size)
{
    size_t slot;
    for (slot = size / 2; slot > 0; --slot)
        sift_down(priorities, size, slot);
}

Output:

build_heap_off_by_one: heapify starts at n / 2 instead of n / 2 - 1
heapify 9, 1, 2 -> peek 9, expected 1
parent 9 > child 1 at slot 0: heap property broken

Heapify must start at the last parent, n / 2 – 1, and finish at slot 0. Starting at n / 2 skips the node that needs repair. Heapifying 9, 1, 2 leaves 9 above 1, so the heap property is broken while the size is right and every insertion path still looks normal. The fix is one index in the loop, and the test must scan every parent-child pair, not just the root.

4. A Stale Index Map

static bool change_priority(Heap *heap, size_t handle, int priority)
{
    size_t slot;
    int old;
    if (handle >= heap->next_handle)
        return false;
    slot = heap->slots[handle];             /* the stale slot */
    if (slot >= heap->size)
        return false;
    old = heap->priorities[slot];
    if (priority == old)
        return true;
    heap->priorities[slot] = priority;
    if (priority < old)
        sift_up(heap, slot);
    return true;
}

Output:

stale_index: the index map is not updated after swaps
push 30, 20, 10 -> size 3, peek 10
change 30 to 5 -> size 3, peek 5
pop order: 5 20 30, expected 5 10 20

The index map is only useful if every swap updates it. Here the map keeps positions from before the sift, so change_priority reads a stale slot and rewrites the wrong element. Size and peek still look plausible. The heap reports size 3 and peek 5, but draining gives 5 20 30 where the correct order is 5 10 20. The values that come out are not the values that went in. The fix is to update both handles inside the swap helper, and the test has to drain the heap after changing a priority.

5. std::priority_queue Is a Max-Heap by Default

// priority_queue_max_default.cpp - DO NOT COPY. std::priority_queue<int> is a
// max-heap: its top() is the largest element, not the smallest. A program
// written as if it were a min-priority queue pops 93 first where the article's
// contract needs 8. The three-argument form
// std::priority_queue<int, std::vector<int>, std::greater<int>> is the min-heap,
// and std::greater is the comparator that reverses the default.
// Build: g++ -std=c++17 -Wall -Wextra -pedantic pitfalls/priority_queue_max_default.cpp -o priority_queue_max_default
#include <cstdlib>
#include <iostream>
#include <queue>

int main()
{
    // No comparator, so the largest priority is served first.
    std::priority_queue<int> queue;
    for (const int priority : {8, 17, 93})
        queue.push(priority);

    std::cout << "priority_queue_max_default: std::priority_queue<int> is a max-heap\n";
    std::cout << "expected min-priority order: 8 17 93\n";
    std::cout << "default std::priority_queue pops:";
    while (!queue.empty()) {
        std::cout << ' ' << queue.top();
        queue.pop();
    }
    std::cout << '\n';
    std::cout << "mismatch: 93 popped first where 8 was expected\n";
    return EXIT_SUCCESS;
}

Output:

priority_queue_max_default: std::priority_queue<int> is a max-heap
expected min-priority order: 8 17 93
default std::priority_queue pops: 93 17 8
mismatch: 93 popped first where 8 was expected

The default std::priority_queue is a max-heap. The program pushes 8, 17 and 93 expecting the smallest first and pops 93, 17, 8, so the first pop is the largest priority where the smallest was expected. In a shortest-path program this returns the farthest node first and the algorithm silently computes the wrong answer. The fix is the third template argument, std::greater<int>, and a test that pushes priorities in both directions.

Key Takeaways

  • A priority queue serves by priority, not by arrival. The binary heap implements it with O(log n) insert and remove and O(1) peek on a plain array.
  • The heap property is one comparison per edge, repaired by sift-up after insertion and sift-down after removal, and both follow a single path.
  • std::priority_queue is a max-heap by default, while heapq, Java’s PriorityQueue and .NET’s PriorityQueue are min-heaps, so check the direction before porting code.
  • No standard priority queue supports decrease-key. Indexed handles give it in O(log n), and pushing duplicates is the workaround that costs memory and stale entries.
  • The linear build won only 19 ms against 21 ms at one million random priorities in C, and 7.6 ms against 10.0 ms with the C++ containers. The asymptotic difference is real, but random insertions stop rising after a level or two.
  • The measured sorted array at 100,000 priorities is 37 times slower than the heap, because every insert and every extract shifts part of the array.
  • Indexed change_priority was 29 ms against 39 ms and 200,000 entries against 300,000 for the duplicate workaround, so decrease-key pays for the index map and wins back the cost in pop time.
  • The straight push-and-pop benchmark was the one place the hand-written heap lost: 280.9 ms against 117.0 ms for std::priority_queue, which is the price of the index map that makes change_priority possible.

Frequently Asked Questions

Conclusion

The priority queue is the smallest data type in this series and the one with the most surprising details. The heap property is one comparison per edge, the array layout needs no pointers, and the two repairs make insert and remove logarithmic. The parts that bite are the direction of the comparison, the 0-based parent formula, the second child in sift-down and the index map that makes change_priority possible.

In production code, reach for the standard container first. C++ needs the extra comparator argument for a min-heap, and every standard library needs the lazy-duplicate workaround for decrease-key. The types of data structures guide places the heap beside the other structures, the data structures hub lists the whole series, and the Heap Sort article takes the same array and turns it into a sorting algorithm.

Source Code and Tests

All programs on this page are in the data-structures/priority-queue directory of the five MYCPLUS example repositories:

LanguageRepository directoryBuild status
Cmycplus/c-examples: data-structures/priority-queueC priority queue build status
C++mycplus/cpp-examples: data-structures/priority-queueC++ priority queue build status
Javamycplus/java-examples: data-structures/priority-queueJava priority queue build status
Pythonmycplus/python-examples: data-structures/priority-queuePython priority queue build status
C#mycplus/csharp-examples: data-structures/priority-queueC# priority queue build status

The C and C++ examples build and test with CMake:

cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure

Java runs with javac --release 17 -Xlint:all -Werror -d build src/*.java tests/*.java followed by java -ea -cp build HeapTest. Python runs with python -m unittest discover -s tests -v, and C# with dotnet build PriorityQueue.slnx -c Release followed by dotnet run --project tests/HeapTests -c Release --no-build.

What the builds check. Every demo’s stdout is compared byte for byte with tests/expected/ordered.txt. The tests compare every operation against a sorted model over at least 100,000 random operations, check the index map and the heap property, and cover change in both directions, duplicates, the linear build, empty heaps and invalid handles. The C and C++ workflows also run the tests, demo and pitfalls under AddressSanitizer and UndefinedBehaviorSanitizer. The builds do not check the timing figures: those belong to one machine and are captured with the article.

What I Verified

The example directories contain the test programs and the captured runs, and the table states which system ran each check.

CheckUbuntu 24.04 (WSL2)Windows 11 (MSVC)
Build and tests, C, GCC 13.3Pass (6 of 6 tests)Not applicable
Build and tests, C, Clang 18.1.3Pass (6 of 6 tests)Not applicable
Build and tests, C, MSVC 19.44 /W4 /WXNot applicablePass (6 of 6 tests)
Build and tests, C++, g++ 13.3Pass (4 of 4 tests)Not applicable
Build and tests, C++, clang++ 18.1.3Pass (4 of 4 tests)Not applicable
Build and tests, C++, MSVC 19.44 /W4 /WX /permissive-Not applicablePass (4 of 4 tests)
Java tests (JDK 21 on WSL, JDK 27 on Windows)Pass (tests and the demo diff)Pass (tests and the demo diff)
Python tests (3.12.3 on WSL, 3.14.6 on Windows), ruff and mypy –strictPass (17 tests and the demo diff)Pass (17 tests, ruff and mypy clean)
.NET build and tests (10.0.115 on WSL, 10.0.404 on Windows)Pass (tests and the demo diff)Pass (tests and the demo diff)
AddressSanitizer and UndefinedBehaviorSanitizer, C and C++ tests, demo and pitfallsPass (C 6 of 6, C++ 4 of 4)Not applicable
Five pitfalls, each caught by the check named in its sectionPass (4 C checks, 1 C++ check)Not applicable
Heap, build, decrease-key and standard-library experimentsRun on Ubuntu 24.04, output in the sections aboveNot run

Not covered: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, Java 17 and 25 locally (the CI matrix covers them), macOS, and timings on any other machine.

Scroll to Top