Study Atlas › Computer Science › Data structures
Heaps and priority queues
A complete binary tree where each parent is ordered relative to its children, giving O(log n) insert and extract-min.
Edited by Alex C, EduAlx · Sources cited below
Explanation
Stored compactly in an array: children of i are at 2i+1 and 2i+2. Heapsort (Williams, 1964) sorts in place in O(n log n). Priority queues power Dijkstra's algorithm, event simulation and task schedulers.
Example
Python's heapq module is a min-heap.
Code
import heapq h = [] for x in [5, 1, 8, 3]: heapq.heappush(h, x) print([heapq.heappop(h) for _ in range(4)]) # [1, 3, 5, 8]
How it works, step by step
- Insert at the end of the array
- Sift up while smaller than parent
- Extract: swap root with last element
- Sift down to restore heap order
Open the interactive page with diagrams →
People behind it
- J. W. J. Williams
- Robert W. Floyd
References
- J. W. J. Williams, Commun. ACM 1964, 7, 347–348.
Textbooks
- Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein (MIT Press, 4th ed. 2022). 'CLRS', the standard algorithms text.
- Algorithms, Robert Sedgewick, Kevin Wayne (Addison-Wesley, 4th ed. 2011). Practical algorithms with Java code.
Related topics
Data structures: arrays, linked lists, stacks, queuesTrees and binary search treesHash tablesGreedy algorithms and minimum spanning treesRecursionString algorithms and pattern matchingNumber systems and data representationAutomata and formal languagesBlockchain and distributed ledgersMemory hierarchy and caches