Examine heap structures, their key operations, and applications in efficient data management and priority queue implementation.
A heap is a nearly complete binary tree in which each node satisfies an order property with respect to its children. It allows immediate access to the minimum (or maximum) element and insertion or removal of one in logarithmic time: it is the structure behind priority queues and a well-known sorting algorithm [1].
In a min-heap each node is less than or equal to its children, so the root is the minimum; in a max-heap the opposite holds. The tree is complete at all levels except the last, which is filled from left to right, and is stored in an array: the node at position $i$ (starting from $1$) has children at $2i$ and $2i+1$ and parent at $\lfloor i/2 \rfloor$. No pointers are needed (see the line on binary trees) [1][2].
Insert the values $5, 3, 8, 1, 9, 2, 7$ in order into a min-heap (assumed values). Each new element goes at the end of the array and "bubbles up" by swapping with its parent as long as it is smaller. At the end the array is $[1, 3, 2, 5, 9, 8, 7]$ (calculation): each parent is smaller than its children, but the array is not sorted.
To extract the minimum, remove the root, move the last element to its place, and "bubble down" by swapping it with the smaller child. Extracting all elements one by one yields $1, 2, 3, 5, 7, 8, 9$ (calculation): this is heapsort, which sorts $n$ elements in $O(n \log n)$ without additional memory.
Starting from the last internal node and bubbling down each node builds the heap in $O(n)$ and not in $O(n \log n)$: most nodes are close to the leaves and move down only a little.
Reading the minimum in $O(1)$, insertion and extraction in $O(\log n)$, because the height is $\lfloor \log_2 n \rfloor$. With $n = 10^6$ elements at most $19$ swaps are needed per operation (calculation).
Priority queues for process scheduling, Dijkstra’s algorithm with heap (see the line on Dijkstra), Huffman coding, merging sorted lists, and finding the $k$ largest elements in a stream (general observation).
It does not allow efficient search for an arbitrary element, nor traversal of data in order without extraction. It is not a binary search tree: the two orders are different. Heapsort is not stable and has poor cache locality compared to other sorting algorithms.
[1] Wikipedia (it): Heap
[2] Wikipedia (en): Heap (data structure)
Generating summary…