Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ The sorting workshop
EXPERIMENT 26 / 66

Drain the priority order.

Separate linear-time heap construction from logarithmic repeated removals.

BY NAVAN SAMI◷ 8 MIN READCOREALGORITHM

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 THING THAT MUST STAY TRUE

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.

the_strategy.txt
BUILD a min-heap from the values
REPEATEDLY remove its minimum
APPEND each removed value to output

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

heap_sort.py
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)
↳ EXPECTED OUTPUT
[1, 1, 5, 7]
[7, 1, 5, 1]
  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. 2

    Each pop restores the heap invariant after removing the root. n removals give O(n log n) total sorting time.

  3. 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

TIME

O(n log n)

SPACE

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

A SMALL MISSION

Confirm that heap_sort preserves duplicates and leaves an empty list empty.

Reveal one possible solution +
one_possible_solution.py
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

QUICK SIGNAL CHECK

What is the cost of heapify on a list?

ANOTHER PATTERN IN YOUR TOOLKIT.

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.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.