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

  1. Insert at the end of the array
  2. Sift up while smaller than parent
  3. Extract: swap root with last element
  4. Sift down to restore heap order

Open the interactive page with diagrams →

People behind it

References

  1. J. W. J. Williams, Commun. ACM 1964, 7, 347–348.

Textbooks

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