Sorting Algorithms
Python's sorted() is excellent (Timsort, O(n log n)). Interviews still ask how sorting works, so let's build a few.
Sorted data makes many problems easy: duplicates sit together, binary search works, and the closest pairs are neighbours. You'll usually use the built-in sort (O(n log n)), but knowing how merge sort and quick sort work is essential for interviews and for understanding performance.
Insertion sort - O(n²), great for small or nearly sorted lists
Example
Merge sort - O(n log n), divide and conquer
Example
Quick sort - O(n log n) on average
Example
Sorting with a key
Example
A sort is stable if equal items keep their original order. Merge sort and Python's sort are stable; quick sort usually isn't.
Key points
- Built-in sort is O(n log n) and stable in Python.
- Merge sort always O(n log n); quick sort O(n log n) on average.
- Sort with a key function for custom orders.
📝 Test yourself
1. What is merge sort's time complexity?
2. Which sort is good for an almost-sorted small list?
3. Fill in the argument that sorts from largest to smallest:
sorted(nums, =True)
