Selection sort builds the sorted array from the front, one position at a time: find the smallest value in the unsorted part, and swap it into the next position. It's how most people sort a handful of cards on a table.
i = 0, scan from i to the end and remember the index of the smallest value.i. Positions 0..i are now sorted and final.i = 1, 2, … until only one value is left — it must be the largest.min tracks the smallest value found so far; the swap happens once per round.
function selectionSort(nums) { const n = nums.length; for (let i = 0; i < n - 1; i++) { let min = i; for (let j = i + 1; j < n; j++) { if (nums[j] < nums[min]) min = j; // remember the smallest so far } [nums[i], nums[min]] = [nums[min], nums[i]]; // put it at the front of the unsorted part } return nums;}Every round scans the whole unsorted part, sorted input or not: (n − 1) + (n − 2) + … + 1 ≈ n²/2 comparisons, so O(n²) in every case. Its one strength is that it makes at most n − 1 swaps — useful when writing to memory is much more expensive than reading. Extra space is O(1).
[2a, 2b, 1] swaps 2a to the end, giving [1, 2b, 2a].When swaps are costly and n is small. Otherwise insertion sort is better for small arrays, and O(n log n) sorts for everything else. The find the minimum of the rest idea, though, is everywhere — it's what a heap makes fast in heap sort.