Data Structures · Priority Queues

A priority queue built on a heap

A heap is a complete binary tree stored in an array. In a max-heap every parent is at least as large as its children, so the highest priority item is always at index 0. Insert and remove each move one item up or down a single path, which takes O(log n) steps. Click any node to see how its index finds its parent and children.

The tree

The same heap as it is stored: vector<int> hT. Level by level, left to right. A dashed red edge means the heap property is broken there.

What is happening

Selected node

Output

    Big-O: array, linked list or heap?

    The class page asks for the cost of each operation. Try it yourself first.

    ImplementationAddRemove topPeek
    Unsorted array or listO(1)O(n)O(n)
    Sorted array (top at the end)O(n)O(1)O(1)
    Sorted linked list (top at the head)O(n)O(1)O(1)
    HeapO(log n)O(log n)O(1)

    PriorityQueue.cpp