Sorting means putting items in order by some key — numbers from smallest to largest, names alphabetically, orders by date. It's the most used algorithm in programming, and in interviews it's one of the most useful tricks: once data is sorted, a hard question often becomes an easy scan.
Sorted data has structure that unsorted data doesn't, and many algorithms depend on it:
ORDER BY, leaderboards, file listings and search results are all sorts.a < b). Bubble, selection, insertion, merge, quick and heap sort all work this way.No comparison sort can beat O(n log n) comparisons in the worst case. There are n! possible orders of n items, and each comparison has two outcomes, so at best it rules out half of the orders still possible. Telling all n! apart needs at least log₂(n!) comparisons — about n log₂ n. Merge sort and heap sort reach that limit; the simple sorts take O(n²). Only non-comparison sorts go faster, and they need extra facts about the values (small integers, a fixed number of digits).
You'll rarely write a sort from scratch at work — every language has a fast, well-tested one. Know how to call it, and how to pass your own comparator: a function that returns a negative number when a should come first, a positive one when b should, and 0 when they're equal.
function sortNumbers(nums) { return [...nums].sort((a, b) => a - b); // without (a, b) => a - b, JS compares as text: [10, 9, 1] -> [1, 10, 9]}Sorting by a key looks the same in every language — tell the sort what to compare:
JavaScript people.sort((a, b) => a.age - b.age)
Python people.sort(key=lambda p: p.age)
Java people.sort(Comparator.comparingInt(p -> p.age))
C++ sort(people.begin(), people.end(), [](auto& a, auto& b) { return a.age < b.age; })The rest of this introduction opens up the classic algorithms one at a time — each drawn, simulated and timed — so you know what these built-ins do and when to write your own.
sort a comparator for numbers — the default compares them as text.Was this helpful?