Module 7 · Sorting · Lesson 24 of 40
Fast sorts: merge, quick, heap and counting
The O(n log n) sorts and when each is used, a sort that doesn't compare at all, and Python's own sorted().
In this lesson · about 22 minutes
- Compare merge sort, quick sort and heap sort
- Explain how counting sort avoids comparisons
- Use sorted() and key= in Python
Merge sort
You met it in Module 6: split in half, sort each half, merge. Always O(n log n) and stable, but it needs O(n) extra memory for merging.
Quick sort
Pick a pivot value. Move everything smaller to its left and everything bigger to its right. The pivot is now in its final place. Then quick sort each side. On average O(n log n) and in-place, so it is very fast in practice. But with bad pivots (for example, always the biggest), it slows to O(n²). Picking a random pivot avoids this.
Heap sort
Put everything in a heap (Module 8), then take out the smallest again and again. Always O(n log n), in-place, but not stable.
Counting sort: no comparing at all
If the values are small whole numbers (like exam scores from 0 to 100), just count how many of each value there are, then write them out in order. That is O(n + k), where k is the range of values. Faster than any comparison sort, but only for small ranges. Radix sort and bucket sort are related ideas.
Try it · see it work
Merge sort and quick sort, step by step
Pick Merge or Quick. Compare their comparison counts with Bubble on the same list.
Comparisons so far: 0
Step 1 of 33Start: [5, 2, 8, 1, 9, 3, 7, 4].
| Sort | Time (average) | Worst | Extra memory | Stable? |
|---|---|---|---|---|
| Bubble / Insertion | O(n²) | O(n²) | O(1) | Yes |
| Selection | O(n²) | O(n²) | O(1) | No |
| Merge | O(n log n) | O(n log n) | O(n) | Yes |
| Quick | O(n log n) | O(n²) | O(log n) | No |
| Heap | O(n log n) | O(n log n) | O(1) | No |
| Counting | O(n + k) | O(n + k) | O(k) | Yes |
In real Python code: use sorted()
Python's built-in sorted(nums) (new list) and nums.sort() (in place) use Timsort, a clever mix of merge sort and insertion sort. It is O(n log n), stable, and very fast on real data. Use it unless you are practising.
key= tells Python what to sort by: sorted(words, key=len) sorts by length. reverse=True sorts biggest first.
Try it: sorted() with key
Exercise
Counting sort
Write counting_sort(nums, biggest) for whole numbers from 0 to biggest. Count how many times each value appears in a list of size biggest + 1, then build the sorted result from the counts.
Exercise
Sort by a key
Write by_score(players). Each player is a pair (name, score). Return the players sorted with the highest score first. Use sorted with key= and reverse=True.
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 2
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.