Sort Values by Heap Extraction
Core idea
A min-heap stores the smallest item at index zero; each parent is no larger than its children. heapify builds the heap in O(n), and repeatedly heappop extracts minima in O(log n) each, giving O(n log n) total sorting time. Our Python version creates a separate output list; textbook in-place heapsort usually uses a max-heap and swaps the root to the end.
import heapqh = [8, 3, 6, 1]heapq.heapify(h)print(h[0])heapq.heappush(h, 0)print(heapq.heappop(h), h[0])The smallest item is at the root after each operation.
Extract all items
import heapqa = [5, 2, 5, -1]h = a[:]heapq.heapify(h)result = [heapq.heappop(h) for _ in range(len(h))]print(result)print(a)Extracting the minimum repeatedly produces ascending order without changing a.
Common mistake
A heap list is not necessarily fully sorted. Heap extraction is not automatically stable for equal-priority records; use an arrival index as a tie breaker.
Practice
Add (priority, arrival_index, label) entries to a heap and extract them in order.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Heap sort
Check your understanding of heap sort.
What is printed?
import heapqh=[9,1,5]heapq.heapify(h)print(h[0])What is printed?
import heapqh=[2,2,4]print(heapq.heappop(h),len(h))Complexity of heapify?
What does heap ordering guarantee?