MODULE 6.7: HEAPS & HEAP SORT — QUICK EXTREMES & SORTING

A student-friendly guide to Heaps and Heap Sort—how Max-Heaps and Min-Heaps work, how to turn an array into a heap, and how Heap Sort orders items in place.

💡 Summary: Always Knowing the Biggest or Smallest Item Fast

Suppose you have a list of exam scores, tasks, or prices and keep asking, "What is the highest (or lowest) value right now?" A Binary Heap is a special tree (shaped like a filled-in pyramid from top to bottom, left to right) that keeps the biggest item at the top in a Max-Heap, or the smallest item at the top in a Min-Heap.

Even better, a heap fits neatly inside a regular array without needing extra node pointers. Using that structure, Heap Sort pulls out the top item again and again to sort an array right inside its own memory space—without needing an extra copy of the array.

1. Building a Heap & Running Heap Sort
When a heap is stored in a 0-based array of size n, you can jump between family members using simple index math—no pointers needed:
  • Parent & Child Formulas: For any item at index i, its parent is at (i - 1) // 2, its left child is at 2 * i + 1, and its right child is at 2 * i + 2.
  • Turning an Array into a Max-Heap (heapify): Leaf items at the bottom have no children, so we start from the last non-leaf node (n // 2 - 1) and move up to index 0, pushing any smaller parent down below larger children.
  • How Heap Sort Works: Once a Max-Heap is built, the largest number is at index 0. Swap it with the last item in the unsorted part, shrink the active heap by one, and push the new root down into its right spot—repeating until the whole array is sorted.
Operation Time Complexity Extra Space What to Remember for Exams
Build Heap (Bottom-Up) O(n) O(1) Faster than inserting n items one by one (O(n log n))
Insert or Remove Top O(log n) O(1) At most one swap per tree level as an item bubbles up/down
Heap Sort O(n log n) O(1) Predictable speed in all cases, though it is not a stable sort
Python (heapify_and_heap_sort.py)
def sift_down_max(arr, n, i):
    largest = i
    left = 2 * i + 1
    right = 2 * i + 2

    if left < n and arr[left] > arr[largest]:
        largest = left
    if right < n and arr[right] > arr[largest]:
        largest = right

    if largest != i:
        arr[i], arr[largest] = arr[largest], arr[i]
        sift_down_max(arr, n, largest)

def build_max_heap(arr):
    n = len(arr)
    for idx in range(n // 2 - 1, -1, -1):
        sift_down_max(arr, n, idx)
    return arr

def heap_sort(arr):
    n = len(arr)
    build_max_heap(arr)
    for end in range(n - 1, 0, -1):
        arr[0], arr[end] = arr[end], arr[0]  # Put largest at the back
        sift_down_max(arr, end, 0)           # Fix the remaining heap front
    return arr

sample = [12, 11, 13, 5, 6, 7]
heap_copy = build_max_heap(sample.copy())
sorted_copy = heap_sort(sample.copy())

print("Original Array :", sample)
print("Max-Heap Array :", heap_copy)
print("Heap Sorted    :", sorted_copy)
Output: Original Array : [12, 11, 13, 5, 6, 7] Max-Heap Array : [13, 12, 7, 5, 6, 11] Heap Sorted : [5, 6, 7, 11, 12, 13]
2. Clever Trick: Tracking a Running Median with Two Heaps
A classic interview and coding-round trick uses two heaps together—a Max-Heap for the smaller half of numbers and a Min-Heap for the larger half:
  • Keep the Two Halves Balanced: Make sure the two heaps differ in size by at most 1 item, and every number in the Max-Heap is smaller than or equal to every number in the Min-Heap.
  • Read the Middle Quickly: If both heaps have the same count, the median is the average of their two top numbers; if one has one extra item, its top number is the median.
C++ (two_heaps_running_median.cpp)
#include 
#include 
#include 
using namespace std;

class MedianFinder {
private:
    priority_queue lowerMax;                               // Max-heap for smaller half
    priority_queue, greater> upperMin;    // Min-heap for larger half

public:
    void addNum(int num) {
        if (lowerMax.empty() || num <= lowerMax.top()) {
            lowerMax.push(num);
        } else {
            upperMin.push(num);
        }

        // Balance sizes so lowerMax has at most 1 extra item
        if (lowerMax.size() > upperMin.size() + 1) {
            upperMin.push(lowerMax.top());
            lowerMax.pop();
        } else if (upperMin.size() > lowerMax.size()) {
            lowerMax.push(upperMin.top());
            upperMin.pop();
        }
    }

    double findMedian() const {
        if (lowerMax.size() > upperMin.size()) {
            return static_cast(lowerMax.top());
        }
        return (lowerMax.top() + upperMin.top()) / 2.0;
    }
};

int main() {
    MedianFinder mf;
    vector stream = {5, 15, 1, 3, 2, 8};
    cout << "Running medians: ";
    for (int x : stream) {
        mf.addNum(x);
        cout << mf.findMedian() << " ";
    }
    cout << "\n";
    return 0;
}
Output: Running medians: 5 10 5 4 3 4
3. 10 Real-Time Examples (Part 1: Examples 1 to 5)
Here are five real-world situations where heaps and Heap Sort come in handy:
  • 1. Sorting When Memory Is Tight (Heap Sort): Sorts data right inside the existing array without needing extra memory for a full temporary copy.
  • 2. Live Middle Value (Running Median): Useful when tracking typical response times or scores as new numbers arrive one by one.
  • 3. Finding the Top-K Items in a Stream: Keeps track of the top 3 or top 10 highest scores or most common errors without storing everything in sorted order.
  • 4. Picking the Most Urgent or Earliest Task: A Min-Heap lets a scheduler grab whichever task has the earliest deadline or highest urgency next.
  • 5. Combining Multiple Sorted Lists: A small Min-Heap helps pick the next smallest item across several sorted lists smoothly.
Python (realtime_heap_apps_1_to_5.py)
import heapq

# 3. Finding the Top-3 Most Frequent Error Codes Using a Min-Heap
class TopKTracker:
    def __init__(self, k):
        self.k = k
        self.min_heap = []  # Stores (count, code)

    def update_counts(self, counts_dict):
        self.min_heap = []
        for code, cnt in counts_dict.items():
            if len(self.min_heap) < self.k:
                heapq.heappush(self.min_heap, (cnt, code))
            elif cnt > self.min_heap[0][0]:
                heapq.heapreplace(self.min_heap, (cnt, code))
        return sorted(self.min_heap, reverse=True)

error_counts = {"E404": 18, "E500": 94, "E401": 42, "E503": 67, "E429": 12}
tracker = TopKTracker(k=3)
print("3. Top-3 Error Codes:", tracker.update_counts(error_counts))
Output: 3. Top-3 Error Codes: [(94, 'E500'), (67, 'E503'), (42, 'E401')]
4. 10 Real-Time Examples (Part 2: Examples 6 to 10)
Five more real-world places where heaps make algorithms faster:
  • 6. Shortest Route Finder (Dijkstra's Algorithm): Helps pick the closest unvisited stop next when finding shortest paths on a map or network.
  • 7. Connecting Networks at Minimum Cost (Prim's Algorithm): Chooses the cheapest next connection to link nodes together.
  • 8. Matching Highest Bids or Closest Drivers: Quickly surfaces the top bid or nearest option from a pool of candidates.
  • 9. Predictable Sorting Without Worst-Case Slowdowns: Unlike basic Quick Sort (which can slow down to O(n²) on tricky inputs), Heap Sort stays at O(n log n).
  • 10. Firing Scheduled Timers in Order: A Min-Heap keyed by time lets an app wake up whichever timer is due soonest.
Python (realtime_heap_apps_6_to_10.py)
import heapq

# 10. Running Scheduled Timers from Soonest to Latest
timers = []
heapq.heappush(timers, (250, "SessionCleanup"))
heapq.heappush(timers, (120, "CacheRefresh"))
heapq.heappush(timers, (180, "MetricsFlush"))

fired = []
while timers:
    due_ms, job = heapq.heappop(timers)
    fired.append(f"{job}@{due_ms}ms")

print("10. Timer Execution Order:", " -> ".join(fired))
Output: 10. Timer Execution Order: CacheRefresh@120ms -> MetricsFlush@180ms -> SessionCleanup@250ms
5. Exam & Study Tips for Students
Watch out for these common mix-ups in exams and coding practice:
  • A heap is NOT a sorted array—and NOT a Binary Search Tree: In a Max-Heap, index 0 is the biggest number, but the rest of the array is only partially ordered for heap rules—not sorted from left to right.
  • Heap Sort is not stable: If two items have the same value, their original relative order might change during swaps.
  • Python's heapq is a Min-Heap by default: To make it act like a Max-Heap for numbers, store -value and flip the sign back when you pop it.
Python (heaps_and_heapsort_checklist.py)
checkpoints = [
    "Heap Shape & Order: Complete binary tree where parent beats (or is beaten by) children.",
    "Build Heap in O(n): Bottom-up heapify builds a heap in linear time.",
    "Heap Sort: O(n log n) time and O(1) extra space, but not stable."
]

for item in checkpoints:
    print("*", item)
Output: * Heap Shape & Order: Complete binary tree where parent beats (or is beaten by) children. * Build Heap in O(n): Bottom-up heapify builds a heap in linear time. * Heap Sort: O(n log n) time and O(1) extra space, but not stable.