Sorting
The simple O(n²) sorts, then merge sort, quick sort and heap sort, and counting sort, which avoids comparing items altogether. You compare them on time, memory and stability.
About 11 hours of study
Learning objectives
- Trace the simple sorts by hand
- Write merge sort and quick sort
- Build a max-heap and sort with it
- Choose a sort from the properties of the data
Lessons
- 1
Bubble, selection and insertion sort
Three O(n²) sorts, step by step: swapping neighbours, picking the minimum, and inserting into a sorted part.
- 2
Merge sort
Divide and conquer: split the array in half, sort each half recursively, and merge two sorted halves in O(n).
- 3
Quick sort
Partition around a pivot, sort each side recursively; O(n log n) on average, O(n²) when the pivots are bad.
- 4
Heap sort and counting sort
Heap sort: O(n log n) in place. Counting sort: O(n + k) without comparing, and why comparison sorts cannot beat n log n.
Module practice
- Insertion sort, pass by passEasy
- Count bubble sort swapsMedium
- Rank students, keeping ties in orderHard
- Repair the mergeEasy
- How many comparisons did merge sort make?Medium
- Count inversions with merge sortHard
- Split around a valueEasy
- One partition stepMedium
- The k-th smallest numberHard
- Sort marks by countingEasy
- Turn an array into a max-heapMedium
- Radix sort, digit by digitHard
Module quiz
‹ Analysis and searchingBacktracking, greedy and dynamic programming ›