Sorting Basics
Read a little, play a little. No scary maths, and no rush.
Sorting as a setup move
Beginners treat sorting as the answer; intermediates treat it as preparation. A sorted array unlocks two pointers, binary search, linear sweeps, and greedy proofs — an O(n log n) investment that regularly turns an O(n²) nightmare into an O(n) stroll. Intervals, meeting rooms, and pair-sum problems all start with sort().
nums = [5, 2, 9, 1]
nums.sort() # in place, Timsort, O(n log n)
intervals = sorted(intervals) # then sweep linearly
What's actually under the hood (the 60-second version)
- O(n²) classics (bubble, selection, insertion): simple, and fine for tiny or nearly-sorted inputs — insertion sort is genuinely used inside real hybrid sorters.
- O(n log n) workhorses (merge, quick, heap): the defaults. Python and Java use Timsort, a merge/insertion hybrid that exploits existing order in real data.
- O(n) specialists (counting, radix, bucket): possible only with constraints like bounded integers — know they exist, rarely implement them live.
Sorting by a key
Real data is rarely a list of plain numbers. Sort records by the field that matters with a key function: sorted(people, key=lambda p: p.age). For a tie-breaker, return a tuple: key=lambda p: (p.age, p.name) sorts by age, then alphabetically within each age. Add reverse=True for largest first. Interval problems almost always begin with intervals.sort(key=lambda iv: iv[0]), ordering by start time.
Stability, and why it matters
A stable sort keeps items that compare equal in their original relative order. Python's sort is stable, and that enables a neat trick: to sort orders by priority and then by date within each priority, sort by date first, then by priority. The second sort keeps the date order inside each priority group. With an unstable sort, that order would be scrambled.
A worked example: can one person attend every meeting?
Given meeting times like [(9, 10), (13, 15), (9.5, 11)], can one person attend them all? Unsorted, you would compare every pair, which is O(n²). Sorted by start time, the list becomes (9, 10), (9.5, 11), (13, 15), and you only need to compare each meeting with the one just before it: does it start before the previous one ends? Here 9.5 is before 10, so the answer is no. Total cost: O(n log n) for the sort plus one linear sweep.
Merge sort and quicksort in a paragraph each
Merge sort splits the list in half, sorts each half, and merges the two sorted halves by repeatedly taking the smaller front item. There are about log n levels of splitting with n work per level, so it is always O(n log n), at the cost of extra memory for merging.
Quicksort picks a pivot, moves smaller items to its left and larger to its right, then sorts each side. It is usually very fast and works in place, but consistently bad pivots degrade it to O(n²), which is why real implementations choose pivots carefully.
The interview calculus
Sorting costs O(n log n), so always ask: does order buy me a cheaper rest-of-solution? If yes (two pointers after sort: O(n log n) total beats O(n²) brute), pay it gladly. If the problem is already solvable in O(n) with a map, sorting first is paying for nothing — say that tradeoff aloud and interviewers notice.
Remember this
- Sort to unlock: two pointers, binary search, interval sweeps, greedy.
- Name Timsort for Python/Java; know O(n) sorts need constraints.
Check your understanding
5 questions · first-try answers earn the most XP
My notes
Saved in this browser. Highlight a line above and save it, or write it in your own words.
Nothing saved yet. Your highlights will live here.
References
Finished reading?
Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.
Related chapters
Spotted a mistake or want a topic covered? Report an issue