"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 , 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
- Learning objectives
- The heap property and its array representation
- Maintaining the heap property: max-heapify
- Building a heap in linear time: build-max-heap
- Heapsort
- The priority queue ADT
Before you start
The full lesson, with worked examples and exercise solutions, is for members.
Read the full lessonNew to SelfMadeQuant.com? See membership options or explore the curriculum.