Visualized DSA Strategies
Episode 7 Sorting
The complete guide to sorting for coding interviews, in JavaScript. First the theory: what sorted and stable mean, what sorting unlocks, what every classic sort costs, why the fast ones are O(n log n), how to sort anything in JavaScript (with no comparator, sort compares items as strings; V8's sort is TimSort: stable, in place, and O(n) on data already in order), comparators that return a number, and five traps. Then nine techniques, each worked as a small problem in full: examples, the brute force animated beside the running line of code, the complete code, every line explained, and the better solution the same way.
What you'll learn
- Sorted and stable: what they mean and when stability matters
- Bubble, selection, insertion, merge, quick, heap and counting sort, and what each costs
- Why merge sort is O(n log n): log n levels of n work
- sort with a comparator (a − b, never the default string order), copying first with a spread or toSorted, ties with ||, localeCompare and typed arrays
- Insertion sort on nearly sorted input, and merge sort step by step
- Partition and quickselect for the k-th largest in O(n) on average
- Counting sort: O(n + k) with no comparisons
- Sort first: two pointers, neighbour checks, interval sweeps, sort-and-scan
- Counting inversions while merge sorting
Chapters
Quiz: test yourself
The 5 questions from the end of the episode. Pick an answer to see why it's right.