Workspace Heap Sort
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Heap Sort visualizer

Return an ascending copy by building a max heap, then moving its maximum to the end of the remaining heap.

EXECUTION LAB

Return an ascending copy by building a max heap, then moving its maximum to the end of the remaining heap.

Input and constraints
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
a = values.copy()
size = len(a)
start = (size // 2)
while ((start > 0) or (size > 1)):
if (start > 0):
start = (start - 1)
root = start
else:
size = (size - 1)
a[0], a[size] = a[size], a[0]
root = 0
while (((root * 2) + 1) < size):
child = ((root * 2) + 1)
if (((child + 1) < size) and (a[child] < a[(child + 1)])):
child = (child + 1)
if (a[root] >= a[child]):
break
a[root], a[child] = a[child], a[root]
root = child
return a

Visualizer

Step 1 of 12
48active16active3

Inspect the current state

Check whether the parent dominates its larger child.

Variable watch

root 1child 3size 5

Step explanation

Check whether the parent dominates its larger child.

comparisons 5reads 2writes 0swaps 0recursiveCalls 0
Educational simulation · O(n log n) time · O(n) returned copy, O(1) auxiliary space

Worked explanation

A tournament repeatedly moves its champion to the winners row and repairs the bracket.

Guided solution

Sift each parent down to build the heap. Exchanging the root with the last live cell fixes one final output position.

O(n log n) time · O(n) returned copy, O(1) auxiliary auxiliary space

Examples

Worked example · {"values":[4,8,1,6,3],"target":0} ⇒ [1,3,4,6,8]

Edge case 1 · {"values":[],"target":0} ⇒ []

Edge case 2 · {"values":[3,3],"target":0} ⇒ [3,3]

Progressive hints

Hint 1A tournament repeatedly moves its champion to the winners row and repairs the bracket.
Hint 2Sift each parent down to build the heap. Exchanging the root with the last live cell fixes one final output position.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

Sifting into the already sorted suffix can destroy final placements.

Interview follow-up

Why does bottom-up heap construction take linear time?

Continue learning

Practice related DSA questions in the same topic.