Courses / Computer Science I
Data Structures

Heaps and Priority Management

Computer Science I 206 words Free to read

Always Serving the Most Urgent

Sometimes you need the most important item first, not the oldest. A priority queue serves elements by priority rather than arrival. The structure that implements it efficiently is the binary heap.

A binary heap is a complete binary tree (filled level by level, left to right) satisfying the heap property:

Heap TypeRoot ElementParent-Child Rule
Max-HeapMaximumParent \ge Children
Min-HeapMinimumParent \le Children

The extreme element is always available in O(1)O(1) time at the top.

Operations and Layout

Insertion and removal maintain the heap property via sifting in O(logn)O(\log n) time:

Because the tree is complete, store it in a plain array: node ii has children at 2i+12i+1 and 2i+22i+2.

Common pitfall: Expecting a heap to be fully sorted. It is only partially ordered—parents relate to children, but siblings and cousins are unordered. Heaps give fast access to the extreme element, powering Dijkstra's and heapsort.
Insert climbs by swapping with its parent; remove sinks the same way

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

10practice questions
2interactive scenes

Data Structures