Courses / Computer Science I
Data Structures

Heaps and Priority Management

Computer Science I 295 words Free to read

Always Serving the Most Urgent

Sometimes you need not "oldest first" (a queue) but "most important first." The priority queue ADT serves elements in order of priority rather than arrival: you insert items with priorities, and each removal returns the highest- (or lowest-) priority item. 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) that satisfies the heap property: in a max-heap, every parent is greater than or equal to its children, so the maximum sits at the root; a min-heap is the mirror, with the minimum at the root. The extreme element is therefore always available in O(1)O(1) at the top.

Insertion and removal keep the heap property by "bubbling":

A neat implementation detail: because the tree is complete, a heap is stored compactly in a plain array, with a node at index ii having children at 2i+12i+1 and 2i+22i+2 — no pointers needed. Heaps power priority scheduling, Dijkstra's shortest paths, and the O(nlogn)O(n \log n) heapsort.

Common pitfall: expecting a heap to be fully sorted. It is only partially ordered — the heap property relates each parent to its children, but siblings and cousins are unordered. A heap guarantees fast access to the single extreme element, not a sorted sequence; to get sorted output you must repeatedly remove the root.

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
Start Computer Science I free

Data Structures