Sorting — The Complete Guide
Master sorting as a problem-solving tool from first principles. Learn to recognize when sorting unlocks simpler solutions, build custom comparators, and confidently tackle interview questions.
Intuition from Scratch
Why does this pattern exist?
Sorting is rarely the final answer to a problem. But it's often the first step that makes the real algorithm possible. Think of it this way: an unsorted array is chaos — you can't make assumptions about where anything is. A sorted array is structured — duplicates are adjacent, neighbors are meaningful, and you can use binary search, two pointers, or greedy strategies that would be impossible on random data.
The cost of sorting is O(n log n). That sounds expensive, but it's almost always worth it when the alternative is O(n²) brute force. Sorting is the "unlock" that drops your overall complexity. And in many interview problems, the interviewer expects you to sort first — it's the natural starting move.
Beyond standard sorting, custom comparators are the secret weapon. When the default numeric or alphabetical order isn't what you need, you define your own ordering rule. Problems like "Largest Number" or "Custom Sort String" are impossible without this skill.
Analogies to Build Intuition
The Library Shelf
Imagine a library where books are thrown randomly on shelves. Finding a specific book means scanning every shelf. But if books are sorted by title, you can jump straight to the right section. Sorting is the librarian's first job — it makes every future lookup fast.
Sorting a Hand of Cards
When you pick up a hand of cards, the first thing you do is sort them by suit and rank. You don't play with a random hand — sorting lets you instantly see what you have, spot pairs, find straights, and make decisions. That's exactly what sorting does for algorithms.
The Priority Queue at a Hospital
Patients aren't treated in arrival order — they're sorted by severity. A custom comparator decides the order: 'compare by severity first, then by arrival time.' That's a custom sort — you define what 'comes first' means for your specific problem.
What kind of problems does it solve?
Sorting is your go-to when:
- You need to merge or detect overlapping intervals
- You need to find duplicates or closest neighbors
- You need a greedy strategy that requires processing in a specific order
- You need to enable Two Pointers or Binary Search on unsorted data
- You need a custom ordering (largest number, custom sort string, relative sort)
- You want to reduce O(n²) brute force to O(n log n)
The core insight
Sorting transforms chaos into structure. Once data is ordered, patterns emerge: duplicates cluster together, neighbors become meaningful, and greedy choices become provably correct. The O(n log n) cost is almost always a worthwhile investment.