Heap Sort for GATE: Build-Heap, Full Trace and Exam Practice
Make heap sort mechanical with one fully traced array, clear heap boundaries, a linear-time build explanation and three original exam-style drills.
KnowledgeGate Team
Exam prep & CS education

Heap sort is often memorised as a sequence of array swaps. That approach is fragile: one wrong child index or heap boundary can spoil the entire trace. Heap sort becomes mechanical when the max-heap invariant, bottom-up construction, repeated extraction and complexity argument are handled separately. The running input is A = [4, 10, 3, 5, 1], stored with 0-based indexing, and the goal is ascending order.
What heap sort is really maintaining
A binary heap is a complete binary tree stored compactly in an array. For a node at 0-based index i, its children are at left = 2i + 1 and right = 2i + 2; its parent is at floor((i - 1) / 2). In the running array, index 0 holds 4. Indices 1 and 2 hold its children 10 and 3, while indices 3 and 4 hold the children 5 and 1 of value 10.
A max-heap maintains A[parent] >= A[child]. Ascending heap sort needs this invariant because the root is then the largest value in the active heap, ready to move to the right end. A min-heap naturally supports extraction in the opposite direction.
A heap is not a binary search tree. Completeness fixes the heap's shape, but it does not impose left-smaller and right-larger ordering. Only the parent-child priority relation is guaranteed.
For cross-family comparisons and selection criteria, use Sorting Algorithms: Complete Guide with Worked Examples for GATE CS and Interviews. For heap sort itself, max-heap construction plus an extraction trace makes the shrinking boundary explicit.
Heapify, build-heap and heap sort are three different jobs
heapify(A, heapSize, i) repairs the subtree rooted at i when its child subtrees are already heaps. Compare i with its valid children, swap with the largest value if required, then continue down only that path. The limit is heapSize, not the physical array length, because the suffix beyond it is already sorted.
buildMaxHeap(A):
for i = floor(n / 2) - 1 down to 0:
heapify(A, n, i)
heapSort(A):
buildMaxHeap(A)
for end = n - 1 down to 1:
swap A[0], A[end]
heapify(A, end, 0)Before an extraction whose last active index is end, A[0:end + 1] is a max-heap and A[end + 1:n] is already in final ascending order. After the root-end swap, only the first end entries remain active, so heapify receives heapSize = end. Keeping that invariant visible prevents boundary mistakes. For a focused prerequisite, revise binary heaps, build-heap, heapify and deletion.
Full worked trace for A = [4, 10, 3, 5, 1]
The last non-leaf index is floor(5 / 2) - 1 = 1, so bottom-up construction starts there.
At
i = 1, value10already dominates its children5and1. The array remains[4, 10, 3, 5, 1].At
i = 0, the larger child is10, so swap4and10:[10, 4, 3, 5, 1].Continue from index
1. Its larger child is5, so swap4and5:[10, 5, 3, 4, 1].
The result is a max-heap: 10 dominates 5 and 3, while 5 dominates 4 and 1.
![Side-by-side array and complete-binary-tree views show max-heap construction from [4, 10, 3, 5, 1], ending with [10, 5, 3, 4, 1] and root 10.](https://cdn.knowledgegate.ai/blog-assets/blog_asset_1784454750617_ydwy0g.jpg)
Now extract the maximum repeatedly. The vertical bar separates the active heap from the fixed suffix.
end = 4: swap root and last to get[1, 5, 3, 4 | 10]. Compare1with5and3, swap it with5, then compare it with child4and swap again. Result:[5, 4, 3, 1 | 10].end = 3: swap to get[1, 4, 3 | 5, 10]. Swap1with larger child4. Result:[4, 1, 3 | 5, 10].end = 2: swap to get[3, 1 | 4, 5, 10]. The active root3already dominates1, so no further swap is needed.end = 1: swap to get[1 | 3, 4, 5, 10].
The final ascending array is [1, 3, 4, 5, 10].
![Four-panel max-heap extraction trace shows active heaps [5, 4, 3, 1], [4, 1, 3], [3, 1], and [1] beside growing fixed sorted suffixes.](https://cdn.knowledgegate.ai/blog-assets/blog_asset_1784454751479_34hemc.jpg)
Complexity, space and stability without the usual shortcut
One heapify operation follows at most the height of the tree, so it costs O(log n). The n - 1 extractions each perform one heapify, making the sorting phase O(n log n).
Bottom-up build is O(n), not O(n log n), because most nodes are close to the leaves and move only a short distance. In a perfect 15-node heap, 8 leaves move 0 levels, at most 4 nodes move 1 level, 2 move 2 levels, and the root moves 3 levels. The weighted bound is 8 x 0 + 4 x 1 + 2 x 2 + 1 x 3 = 0 + 4 + 4 + 3 = 11. This is intuition for the standard height-sum proof, not an exact count of comparisons.
Property | Standard array-based heap sort |
|---|---|
Best time |
|
Average time |
|
Worst time |
|
Auxiliary space |
|
Stable | No |
In-place | Yes |
Use these distinctions in time-complexity MCQs while the reasoning is fresh.
Trace traps that cost marks
Treating the heap as a BST: compare parents with children, not left-side values with right-side values.
Using 1-based formulas on a 0-based array: the children are
2i + 1and2i + 2, not2iand2i + 1.Starting build at a leaf: leaves are already single-node heaps. Start at
floor(n / 2) - 1.Ignoring the shrinking boundary: after
10moves behind the bar in[1, 5, 3, 4 | 10], heapify only the first four positions. Inspecting index4could pull the fixed maximum back into the heap.
A max-heap is not a fully descending array. Also, bottom-up build is O(n), while building by repeated insertion is O(n log n). Finally, standard heap sort is not stable because distant swaps can reverse equal-key records. For example, sorting (4,a), (2,x), (4,b) does not guarantee that (4,a) remains before (4,b).
How GATE-style questions test the method
These are original exam-style drills, not reproduced previous-year questions.
Drill 1: Delete the maximum
A 0-based max-heap is [50, 30, 40, 10, 5, 20, 35]. What remains after deleting the maximum and restoring the heap?
Move the last value 35 to the root: [35, 30, 40, 10, 5, 20]. Its children are 30 and 40, so swap with the larger child 40. The restored heap is [40, 30, 35, 10, 5, 20].
Drill 2: Read the array formulas
For a complete heap of n = 31 elements stored from index 0, how many internal nodes are there, what is the last non-leaf index, and what is the height in edges?
There are floor(31 / 2) = 15 internal nodes. Their indices are 0 through 14, so the last non-leaf index is floor(31 / 2) - 1 = 14. The height is floor(log2 31) = 4 edges, since indices 0 through 30 fill five levels.
Drill 3: Select the valid property set
Which set describes standard array-based heap sort?
The correct set is: worst-case O(n log n), O(1) auxiliary space with iterative heapify, and unstable. O(n) applies only to bottom-up construction, not the complete sort. Recursive heapify uses stack space, and in-place operation does not imply stability.
The short version and the next practice step
Build a max-heap in O(n). Swap its root with the active end. Shrink the heap, repair the root, and repeat. For our input, that produces the in-place ascending result [1, 3, 4, 5, 10] in O(n log n) time.
For the next step, use GATE Guidance by Sanchit Sir for a broader exam-focused route, DSA using Java for implementation and interview practice, or browse the wider GATE course category. These are optional routes for extending the practice, not prerequisites for understanding heap sort.
Keep learning
Heap Sort Interview Questions and Answers: Trace, Code, and Follow-Ups
Learn to build a max-heap, trace every extraction, explain iterative sift-down, justify the time and space bounds, and handle common Heap Sort follow-ups.
Heap Sort MCQs: 10 Solved Questions with Explanations (GATE, ISRO, DSSSB)
Solve 10 heap sort questions drawn from GATE, ISRO, DSSSB and other papers. Each answer explains the tested fact, shortcut or calculation.
Optimal Merge Pattern Interview Questions and Answers: Greedy Proof, Min-Heap Trace and Code
Learn how to explain and implement Optimal Merge Pattern through one exact heap trace, a correctness proof, common traps and ten concise interview answers.
Selection Sort Explained: Step-by-Step Trace, Complexity and Exam Traps
Learn the invariant behind Selection Sort, trace every pass, derive its exact comparison count, and avoid common stability and swap-count traps.





