Heapsort and Priority Queues
Algorithms · Advanced Placement
Heapsort and Priority Queues: the big picture
A binary heap is an array viewed as a nearly complete binary tree in which every node satisfies a heap property relative to its children: in a max-heap each node is at least as large as its children, and in a min-heap at most as small. The array representation needs no pointers, with a node's children and parent located by simple index arithmetic, which makes heaps compact and cache-friendly. The fundamental operation restores the heap property at a node whose children are already heaps by sifting the node down to its correct level, which costs time proportional to the height and hence logarithmic in the number of elements. Building a heap from an unordered array by sifting down from the last internal node upward costs linear time overall, which is better than the logarithmic-per-element bound suggests because most nodes are near the bottom and sift only a short distance. Heapsort repeatedly exchanges the root with the last element, shrinks the heap and restores the property, sorting in place in linearithmic worst-case time. A heap also implements a priority queue supporting insertion, maximum extraction and key increase in logarithmic time, which is the structure Dijkstra's and Prim's algorithms depend on and which underlies process scheduling and event simulation.
Binary Heaps, Sift-Down & Linear-Time Build
A heap is an array that you read as a nearly complete binary tree, with children and parent found by index arithmetic rather than pointers — which makes it compact and cache-friendly. The one operation that matters is sifting a node down to its correct level, costing time proportional to the height. Building a heap from an unordered array looks like it should cost n log n, but sifting from the bottom up gives linear time, because most nodes are near the bottom and barely move. That counterintuitive result is worth understanding properly.
{{illustration:algos-l05-f1}}
{{illustration:algos-l05-f2}}
Key relations
- Heap indices and build cost. parent(i) = lfloor i/2 rfloor ; left(i) = 2i ; ∑_(h=0)^(lfloor log n rfloor) n/(2^(h+1)) h = O(n)
Heapsort, Priority Queues & Applications
Heapsort exchanges the root with the last element, shrinks the heap by one and restores the property — repeat and the array comes out sorted, in place, with a guaranteed n log n worst case. In practice quicksort usually beats it because heapsort's access pattern jumps around the array and defeats the cache, which is a good illustration that asymptotic equality does not mean practical equality. The heap's other role is as a priority queue, and that is where it earns its keep: Dijkstra, Prim, event simulation and process scheduling all depend on it.
{{illustration:algos-l05-f3}}
{{illustration:algos-l05-f4}}
Key relations
- Heapsort and priority queue bounds. T_heapsort(n) = Θ(n) + n O(log n) = Θ(nlog n) ; T_Dijkstra = O((V + E)log V)