All algorithms
Data Structures

Priority Queue (Binary Heap)

Always pop the largest — a tree hiding inside an array.

TimeO(log n) push/popSpaceO(n)CategoryData Structures

A binary heap is a complete binary tree where every parent outranks its children, stored in a plain array: the children of index i live at 2i+1 and 2i+2. Pushing appends and bubbles up; popping takes the root, moves the last element there and sifts it down. Both cost O(log n) because the tree height is log n.

It is what `std::priority_queue` is, and what makes Dijkstra and A* fast. Draining it fully gives heap sort — O(n log n) with no extra memory.

The array-as-tree trick is the part worth seeing. AlgoLens draws the heap as an actual tree, so bubbling up and sifting down become movements you can follow instead of index arithmetic.

The code

priority_queue.cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
    priority_queue<int> pq;

    for (int x : {5, 2, 9, 1, 7, 3}) pq.push(x);

    while (!pq.empty()) {
        cout << pq.top() << ' ';
        pq.pop();
    }
    cout << '\n';
    return 0;
}
Open this in the visualizer

Now run your own Priority Queue (Binary Heap)

AlgoLens traces your code — arrays, graphs, trees and recursion — from a real execution, so you see how it actually behaves, not a canned animation.

Paste your code

Keep going