Heap Sort
Return an ascending copy by building a max heap, then moving its maximum to the end of the remaining heap.
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 aVisualizer
Step 1 of 12Inspect the current state
Check whether the parent dominates its larger child.
Variable watch
Step explanation
Check whether the parent dominates its larger child.
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 1
A tournament repeatedly moves its champion to the winners row and repairs the bracket.Hint 2
Sift each parent down to build the heap. Exchanging the root with the last live cell fixes one final output position.Hint 3
Step 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?