Sorting
Put data in order - and know what each algorithm costs and keeps stable.
- visited / done
- active this step
- result
Pick 2
Everything left of index 1 - just [5] - is already sorted.
VARIABLES
- i
- 1
- key
- 2
- nums
- [5, 2, 4, 1]
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
Sorting arranges elements by a key. Merge sort and heap sort take O(n log n) in the worst case; simple sorts like insertion sort take O(n²).
Why it matters
Sorted data unlocks binary search, two pointers, interval merging and easy duplicate detection.
Think of it like this
Insertion sort is how most people sort a hand of cards: take the next card and slide it left into place.
Use it when
- Order makes the rest of the problem easy (pairs, intervals, duplicates)
- The output must be ordered
- n is small enough that O(n log n) fits
Avoid it when
- You only need the top k of a huge list - a heap is O(n log k)
- Values are small integers in a known range - counting sort is O(n + k)
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Bubble, selection, insertion | O(n²) | O(1) |
| Merge sort | O(n log n) | O(n) |
| Quick sort (average) | O(n log n) | O(log n) |
Often confused with: heaps - they keep the minimum ready without fully sorting.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- If sorting first is allowed, O(n log n) is often the target
- Stability matters when you sort by one key after another
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Assuming quick sort is always O(n log n) - bad pivots make it O(n²)
- Forgetting sorted() returns a new list while list.sort() sorts in place
- Sorting when one pass or a heap would do
Edge cases to test
- Already sorted input - insertion sort’s best case, O(n)
- Reverse-sorted input - its worst case
- Many duplicates
Knowledge check
Quick check to lock in the intuition.
Which sort is stable and O(n log n) in the worst case?
Practice
Apply what you just watched on real interview problems.