Skip to contentKEEP THE CRAFTTHE SANCTUARY

Heap Sort

Build a max heap over an active array prefix and move each maximum into a finalized ascending suffix. Keep child comparisons and heap boundaries correct, and separate the in-place core from the Lab output copy.

1 practice exercise7 interview problems

Recognize it when Worst-case O(n log n) comparison sorting is needed without merge-buffer storage.

Checking your account…

Heap Sort Code Labs

Build a Max Heap In Place

Heap sort first turns the array into a max heap. Bottom-up heapify starts at the last internal node because leaves already satisfy the heap property.

Swap the Root into Final Position

The root is the maximum remaining value. Swap it with the last position of the active heap, which grows a sorted suffix that will never be touched again.

Trace Max-Heap Construction

Reference
def heapify_trace(values):
    values=values.copy();trace=[];n=len(values)
    def sift(root,end):
        while 2*root+1<end:
            child=2*root+1
            if child+1<end and values[child+1]>values[child]:child+=1
            if values[root]>=values[child]:break
            values[root],values[child]=values[child],values[root];root=child
    for root in range(n//2-1,-1,-1):sift(root,n);trace.append(values.copy())
    return trace
Practice

Implement heapify_trace(values). Return array state after each bottom-up sift-down call.

Public tests

  • Sift internal nodes bottom up

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Max-Heap Construction

def heapify_trace(values):
    values=values.copy();trace=[];n=len(values)
    def sift(root,end):
        while 2*root+1<end:
            child=2*root+1
            if child+1<end and values[child+1]>values[child]:child+=1
            if values[root]>=values[child]:break
            values[root],values[child]=values[child],values[root];root=child
    for root in range(n//2-1,-1,-1):sift(root,n);trace.append(values.copy())
    return trace

Repair Child Subheaps Before the Root

The existing heapify Lab performs only two outer sift calls on four values. Its second call may make two swaps; distinguish outer snapshots from internal repairs.

Step Executed statement State Why
Last internal node for root in range(n//2-1,-1,-1): first root=1 Leaves need no work; node 1 already dominates child 4.
Root children if child+1<end and values[child+1]>values[child]:child+=1 larger root child is index 1, value 5 Promoting the smaller child would violate the max property.
First root swap values[root],values[child]=values[child],values[root];root=child values=[5, 2, 1, 4], root=1 The maximum reaches the root; the displaced 2 may still violate its subtree.
Continue downward values[root],values[child]=values[child],values[root];root=child values=[5, 4, 1, 2] Repair at the new location completes the root subheap.
Snapshot trace.append(values.copy()) two rows, one per outer sift call The Lab records after a complete sift, not after every inner swap.
Print Output
print(heapify_trace([2, 5, 1, 4])) [[2, 5, 1, 4], [5, 4, 1, 2]]

The sorting Lab next transfers maxima into the suffix. Explain the exclusive active end each time; the sorted tail is deliberately no longer a child region.

Restore the Shrinking Heap

After each root swap, sift the new root down only within the shortened heap boundary. Children in the sorted suffix are no longer heap members.

Heap Sort Values

Reference
def heap_sort(values):
    values=values.copy();n=len(values)
    def sift(root,end):
        while 2*root+1<end:
            child=2*root+1
            if child+1<end and values[child+1]>values[child]:child+=1
            if values[root]>=values[child]:break
            values[root],values[child]=values[child],values[root];root=child
    for root in range(n//2-1,-1,-1):sift(root,n)
    for end in range(n-1,0,-1):values[0],values[end]=values[end],values[0];sift(0,end)
    return values
Practice

Implement heap_sort(values). Return an ascending sorted copy using an in-place max heap.

Public tests

  • Move each max root into the suffix

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Heap Sort Values

def heap_sort(values):
    values=values.copy();n=len(values)
    def sift(root,end):
        while 2*root+1<end:
            child=2*root+1
            if child+1<end and values[child+1]>values[child]:child+=1
            if values[root]>=values[child]:break
            values[root],values[child]=values[child],values[root];root=child
    for root in range(n//2-1,-1,-1):sift(root,n)
    for end in range(n-1,0,-1):values[0],values[end]=values[end],values[0];sift(0,end)
    return values

Choose Heap Sort or Merge Sort

Heap sort guarantees O(n log n) with O(1) auxiliary array space but is not stable and has less cache-friendly access. Merge sort is stable and sequential but needs O(n) merge storage in standard arrays.

Explain It in an Interview

Say: “The active prefix is a max heap and the suffix is finalized ascending output. I move the root to the suffix and restore only the active heap.” State O(n) heapify plus O(n log n) extraction.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Bottom-up heapifyO(n)O(n)Most nodes have small sift height.
Complete heap sortO(n log n)O(n log n)Each extraction sifts within a shorter heap.

Space

O(1) auxiliary core state; the sorted-copy Lab uses O(n) copy storage and the trace Lab stores O(n^2) snapshot cells.

Assumptions

  • In-place heapsort is not stable: swaps can reorder equal-key records.
  • Heap layout is a partial order, not a globally sorted array.

Invariants Worth Saying Aloud

  1. Every active parent is at least as large as its active children.
  2. The suffix is finalized ascending output and is outside later sifts.

When To Use Or Avoid Heap Sort

Use It When

  • Use heapsort when stability is unnecessary and the array can be rearranged.
  • Use heapify once instead of inserting every item to construct the initial heap.

Choose Another Tool When

  • Python sorted is simpler for ordinary full ordering and preserves stable ties.
  • For only a few extrema, retain a bounded heap rather than extracting every item.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Selecting the smaller child of a max heap

Promoting 4 while its sibling is 7 leaves the parent below the unchosen child.

Prevent it: Promote the larger active child.

Avoid

child = left if values[left] < values[right] else right

Use instead

child = left if values[left] >= values[right] else right

Allowing the sorted suffix back into a sift

At end=2, index 2 is finalized. Using the full list length treats it as a child and can disturb output.

Prevent it: Compare child indexes with the exclusive active end.

Avoid

has_right = right < len(values)

Use instead

has_right = right < end

Returning heap layout as sorted output

[7,2,5] is a valid max heap but not ascending order. Heapify guarantees a root extreme, not total ordering.

Prevent it: Complete extraction/sortdown before returning an ordered list.

Avoid

result = heap.copy()

Use instead

result = sorted(heap)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.