Skip to content
Data Structures and Algorithms / Linear Structures, Hashing, and the Sorting Toolkit

Heapsort and Priority Queues

"Give me the current top 10 holdings by weight" and "process the next order in price-time priority" are both instances of the same computational primitive: repeatedly extract the largest (or smallest) element from a changing collection, without re-sorting the whole thing each time. The binary heap is the data structure built exactly for this, and heapsort is the Θ(nlog⁡n)\Theta(n\log n), in-place sorting algorithm that falls out of it almost for free. This note builds the heap from its array representation up, derives the running times of heapify, build-heap, and heapsort, and introduces the priority queue ADT the heap supports — the structure Python's heapq module implements directly.

In this lesson

  1. Learning objectives
  2. The heap property and its array representation
  3. Maintaining the heap property: max-heapify
  4. Building a heap in linear time: build-max-heap
  5. Heapsort
  6. The priority queue ADT

Before you start

The full lesson, with worked examples and exercise solutions, is for members.

Read the full lesson

New to SelfMadeQuant.com? See membership options or explore the curriculum.