Drain the priority order.
Separate linear-time heap construction from logarithmic repeated removals.
01 Model the idea
Heap sorting first establishes a heap, then repeatedly removes the minimum to produce ordered output. Building a heap bottom-up can take linear time, even though pushing n individual values has a larger O(n log n) upper bound. This Python example copies values and produces a new output list; it is not the in-place array heapsort variant.
The output prefix is sorted, and every remaining heap value is no smaller than its last item.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
BUILD a min-heap from the values
REPEATEDLY remove its minimum
APPEND each removed value to output03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
import heapq
def heap_sort(values):
heap = list(values)
heapq.heapify(heap)
return [heapq.heappop(heap) for _ in range(len(heap))]
values = [7, 1, 5, 1]
print(heap_sort(values))
print(values)[1, 1, 5, 7] [7, 1, 5, 1]
- 1
heapify modifies the copied list, preserving the caller’s sequence. Its bottom-up work is linear because most nodes are near the leaves.
- 2
Each pop restores the heap invariant after removing the root. n removals give O(n log n) total sorting time.
- 3
A heap gives efficient access to the next extreme, not sorted arbitrary indexing. Choose it for incremental priority operations rather than only because a sorted result is eventually needed.
04 Count the cost
O(n log n)
O(n) copied heap plus output
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Confirm that heap_sort preserves duplicates and leaves an empty list empty.
Reveal one possible solution +
import heapq
def heap_sort(values):
heap = list(values); heapq.heapify(heap)
return [heapq.heappop(heap) for _ in range(len(heap))]
assert heap_sort([2, 1, 2]) == [1, 2, 2]
assert heap_sort([]) == []
print("Heap sorting checks passed")06 Check your reasoning
What is the cost of heapify on a list?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.