Field manual
Elementary sorts (selection, bubble, insertion)
O(n^2)Sort with simple nested-loop passes: repeatedly pick the next-smallest element, swap adjacent out-of-order pairs, or insert each element into its sorted place among what came before.
Signals
n is small (tens or a few hundred)array is nearly sorted alreadysort in place with O(1) extra spaceteaching/interview question about how sorting worksstability matters and simplicity is fine
Template
function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
const key = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
return arr;
}Looks similar, isn't
- Fast sort (merge/quick): Elementary sorts are O(n^2), fine for small n or nearly-sorted input. Once n is large (thousands+) and unordered, the n^2 passes get too slow; you need an O(n log n) sort instead.
n small (roughly under a few hundred) or nearly sorted -> O(n^2) time is acceptable, O(1) space. Once the problem states n in the thousands or more, this stops being the answer.
Learn this pattern