Sorting basics and why order helps
Start with no coding-interview background, learn to trace an algorithm by hand, measure its cost, and finish able to reason about arrays, hashing, trees, graphs, dynamic programming and the trade-offs an interviewer expects you to name.
What you will be able to do
#- Trace selection sort and insertion sort on a small array.
- Explain why comparison sorting is at best O(n log n).
- Use a comparator correctly with a built-in sort.
Overview
#Why sort at all
Order unlocks cheaper algorithms. Binary search needs sorted data. Two pointers and interval merging need sorted data. Sorting is a preprocessing cost that many later steps depend on.
Selection sort
Repeatedly find the smallest remaining element and swap it into place:
for (let i = 0; i < values.length; i++) {
let min = i;
for (let j = i + 1; j < values.length; j++) {
if (values[j] < values[min]) min = j;
}
[values[i], values[min]] = [values[min], values[i]];
}
The nested loops make it O(n^2). It performs O(n) swaps, which is nice when writes are expensive.
Insertion sort
Grow a sorted prefix, inserting each new element into its place:
for (let i = 1; i < values.length; i++) {
const key = values[i];
let j = i - 1;
while (j >= 0 && values[j] > key) {
values[j + 1] = values[j];
j--;
}
values[j + 1] = key;
}
Worst case O(n^2), but near-sorted input is close to O(n). That makes it useful for small or almost-sorted arrays.
The comparison lower bound
Any algorithm that only compares elements needs at least log base 2 of n! comparisons in the worst case, which is O(n log n). Merge sort and heap sort reach this bound. Selection and insertion sort do not.
Built-in sort and comparators
values.sort() sorts by string conversion by default, so [10, 9, 1].sort() gives [1, 10, 9]. Pass a numeric comparator:
values.sort((a, b) => a - b);
A negative result means a comes first, a positive means b comes first, and zero means keep the order.
Practice next
- Trace insertion sort on [5, 2, 4, 1] and list the array after each outer iteration.
- Explain why merge sort is O(n log n).
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does [10, 9, 1].sort() return in JavaScript?
starter.javascriptreturn [10, 9, 1].sort();Reveal the reference answer
reference.javascriptThe default sort compares string forms: '1' < '10' < '9', so it returns [1, 10, 9].Authored expected output: [1, 10, 9]
Always pass (a, b) => a - b for numeric order.
Exercise 2Predict
After the first outer iteration of insertion sort on [5, 2, 4, 1], what is the array?
starter.javascriptfor (let i = 1; i < values.length; i++) { const key = values[i]; let j = i - 1; while (j >= 0 && values[j] > key) { values[j + 1] = values[j]; j--; } values[j + 1] = key; }Reveal the reference answer
reference.javascripti = 1, key = 2. 5 > 2 so shift 5 right and place 2 at index 0. The array becomes [2, 5, 4, 1].Authored expected output: [2, 5, 4, 1]
The sorted prefix after one pass is [2, 5].
Exercise 3Explain
Explain why comparison sorting cannot do better than O(n log n) in the worst case.
Reveal the reference answer
reference.textThere are n! possible orderings of n distinct elements. Each comparison has two outcomes, so k comparisons can distinguish at most 2^k orderings. To cover n! orderings you need 2^k >= n!, which gives k >= log base 2 of n!, and that is O(n log n).Authored expected output: n! orderings and binary comparisons imply log2(n!) = O(n log n) comparisons.
This decision-tree argument is why merge sort and heap sort are asymptotically optimal for comparison sorting.
Common misconceptions
#- sort() sorts numbers correctly by default. It converts to strings, so 10 sorts before 9 without a comparator.
- Insertion sort is always slow. It is near O(n) on nearly sorted data and fast on small arrays.
- A faster computer makes O(n^2) sorting competitive with O(n log n) at scale. The gap grows without bound as n grows.
Follow-up practice
#- dsa-from-zero-two-pointers
- dsa-from-zero-greedy-and-intervals
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.