Module A-2·12 min read

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

Written by Jatin Jain Saraf · Architect of SupraScan

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:

function heapSort(arr: number[]): number[] {
  const n = arr.length;
 
  // Build a max-heap in place: heapify every non-leaf node, from the last one up to the root
  for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
    siftDown(arr, i, n);
  }
 
  // Repeatedly move the current max (always at index 0) to the end, then shrink the heap by one
  for (let end = n - 1; end > 0; end--) {
    [arr[0], arr[end]] = [arr[end], arr[0]];
    siftDown(arr, 0, end); // restore heap property, but only within the shrinking unsorted region [0, end)
  }
 
  return arr;
}
 
function siftDown(arr: number[], i: number, size: number): void {
  let largest = i;
  const left = 2 * i + 1, right = 2 * i + 2;
 
  if (left < size && arr[left] > arr[largest]) largest = left;
  if (right < size && arr[right] > arr[largest]) largest = right;
 
  if (largest !== i) {
    [arr[i], arr[largest]] = [arr[largest], arr[i]];
    siftDown(arr, largest, size);
  }
}

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:

function findKthLargest(nums: number[], k: number): number {
  const minHeap = new MinHeap(); // Module A-1's MinHeap
 
  for (const num of nums) {
    minHeap.insert(num);
    if (minHeap.size() > k) {
      minHeap.extractMin(); // discard the smallest — it can't be among the k largest
    }
  }
 
  return minHeap.peek()!; // the smallest value remaining IS the kth largest overall
}

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...