Module A-2·16 min read

Heap sort, Kth largest element, and merging K sorted lists — where a heap beats a full sort.

JJS
Written by Jatin Jain Saraf · Senior Software Engineer

Module A-2 — Heap Applications: Heap Sort, Kth Largest Element, Merge K Sorted Lists

What this module covers: Module A-1 built the two core heap operations. This module puts them to work on three classic problems, each choosing a heap for a genuinely different reason — sorting in place with no extra memory, avoiding a full sort when only a partial answer is needed, and merging many sorted sources at once without paying for repeated pairwise merges.


Heap Sort: In-Place O(n log n), No Extra Array

Build a max-heap from the entire array, then repeatedly extract the maximum and place it at the end of the shrinking unsorted region:

typescript

Building the max-heap is O(n) (a detail that looks surprising at first — heapifying n/2 nodes at O(log n) each looks like O(n log n), but the math works out to O(n) overall because most nodes are near the bottom of the tree and need very little sifting). The n extractions afterward are each O(log n), for O(n log n) total — matching Modules P-9 and P-10's other O(n log n) sorts, but this one sorts entirely in place, using O(1) extra space (just the swap), unlike merge sort's O(n) auxiliary array requirement. Like quicksort, heap sort is not stable — the swaps involved in sifting can reorder equal elements relative to each other, exactly the same trade-off flagged for quicksort in Module P-10.


Kth Largest Element: A Heap of Size K, Not the Whole Array

Finding the Kth largest element doesn't require fully sorting anything — and a heap makes that explicit, using only a fixed-size min-heap of k elements:

typescript

The heap only ever holds the k largest values seen so far — every time it grows past size k, the smallest of those is discarded, since it's now provably too small to be among the true k largest once one more genuinely-larger candidate has been seen. This runs in O(n log k) — n insertions/extractions, each O(log k) since the heap never exceeds size k — which beats a full O(n log n) sort whenever k is meaningfully smaller than n (finding the top 10 out of 10 million items, for instance, is O(n log 10), not O(n log n)). Module P-10's quickselect (using the same partitioning as quicksort, but recursing into only the one side that contains the target rank) solves the same problem in O(n) average time — genuinely faster on average — but without the min-heap version's O(k) space bound or its natural fit for a streaming input, where you don't have the whole array in memory at once to partition.


Merge K Sorted Lists: One Heap Instead of K Pairwise Merges

Sign in to keep reading

The rest of this module is free — sign in with Google to unlock it and track your progress.

Sign in & Register

Discussion

0

Join the discussion

Loading comments...

© 2026 Jatin Jain Saraf (JJS). All rights reserved.