Skip to content

Trace nested loops and swaps

When tracing code, write down the loop indices, the values being compared, and the array after any mutation. Do not jump to the final answer.

Here is a simple nested-loop sort. It places the smallest remaining value at each index:

function selectionSort(values) {
const result = [...values];
for (let i = 0; i < result.length - 1; i++) {
for (let j = i + 1; j < result.length; j++) {
if (result[i] > result[j]) {
[result[i], result[j]] = [result[j], result[i]];
}
}
}
return result;
}

Trace the first two outer-loop passes for [4, 2, 1, 2, -7]:

Step i j Comparison Array after step
Start — — — [4, 2, 1, 2, -7]
1 0 1 4 > 2, swap [2, 4, 1, 2, -7]
2 0 2 2 > 1, swap [1, 4, 2, 2, -7]
3 0 3 1 > 2, no [1, 4, 2, 2, -7]
4 0 4 1 > -7, swap [-7, 4, 2, 2, 1]
5 1 2 4 > 2, swap [-7, 2, 4, 2, 1]
6 1 3 2 > 2, no [-7, 2, 4, 2, 1]
7 1 4 2 > 1, swap [-7, 1, 4, 2, 2]

At the end of the first outer pass, the minimum value is at index 0. At the end of the second, the next minimum is at index 1. The remaining passes complete the result [-7, 1, 2, 2, 4].

  • i marks the position currently being filled.
  • j scans the values to its right.
  • The comparison decides whether to swap; equality does not swap here.
  • A swap changes the array immediately, so the next comparison sees the changed values.

The algorithm performs O(n²) comparisons. Try tracing [3, 1, 2] yourself and record the array after each comparison.