Problem in simple words
Given an array, sort it by repeatedly selecting the smallest value from the unsorted suffix.
Core idea
Treat the left side as done. For each position, search the rest of the array for the smallest remaining value and lock it into place.
How the algorithm thinks
- 1
Search the suffix for the minimum
COMPAREThe sorted prefix is fixed. The inner scan only asks which remaining value should occupy the next position.
Watch: minIndex and each suffix comparison.
- 2
Lock the next prefix position
UPDATEAfter the minimum is known, swap it into the boundary so the sorted prefix grows by one.
Watch: Boundary index and selected minimum value.
- 3
Leave the fixed prefix alone
DISCARDValues before the boundary are already among the smallest values in sorted order, so the scan should not disturb them.
Watch: Sorted prefix marker.
- 4
Finish when the suffix is exhausted
RETURNOnce every position has been selected, the whole array is sorted.
Watch: Final sorted array.
Step-by-step logic
- -For each index i from 0 to n - 2, set minIndex = i.
- -Scan j from i + 1 to n - 1.
- -Update minIndex when nums[j] is smaller.
- -After the scan, swap nums[i] with nums[minIndex].
- -Continue until the suffix has one value left.
Complexity
Time O(n^2)·Space O(1)
Every pass scans the remaining suffix, producing about n^2 comparisons, while sorting happens in place with only a few index variables.
Implementation
This is the JavaScript implementation that generates the simulator timeline.
function selectionSort(arr) {
for (let i = 0; i < arr.length - 1; i++) {
let minIndex = i;
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex !== i) {
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
}
return arr;
}Common mistakes
Pause before the next step and name the state change you expect.
Watch the active pointers, discarded range, and output state and match it to the highlighted code line.
Say the rule that never breaks (the invariant) out loud: what remains true before and after this step?
- -Step 1: i=0. Scan the suffix [64, 25, 12, 22, 11] for the minimum: 11 at index 4. Swap with index 0 -> [11, 25, 12, 22, 64].
- -Step 2: i=1. Scan the suffix [25, 12, 22, 64] for the minimum: 12 at index 2. Swap with index 1 -> [11, 12, 25, 22, 64].
- -Step 3: i=2. Scan the suffix [25, 22, 64] for the minimum: 22 at index 3. Swap with index 2 -> [11, 12, 22, 25, 64].
- -Step 4: i=3. Scan the suffix [25, 64]: the minimum, 25, is already at index 3, so no swap is needed. Array is sorted.
- - Decide what each pointer represents.
- - Move the pointer that can safely eliminate work.
- - Keep the invariant true after every move.
Build the reasoning before opening the simulator
Turn the mental model into a short decision checklist, then compare it with the execution timeline.