Bubble sort, from the previous lesson, swaps a lot: one big number can be swapped many times before it reaches its place. Selection sort makes far fewer swaps. Selection sort finds the smallest number first, and only then puts it at the front with a single swap. Then it finds the smallest of what's left, puts it in second place, and so on. It's like laying out number cards on a table: take the smallest card first and put it at the far left, then take the smallest of the rest.
How it works
Sort [64, 25, 12, 22, 11]. One pass fills one position, starting from the left: find the smallest number in the unsorted part, then swap it once with the number at the front of that part.
| Pass | What happens | Array afterwards |
|---|---|---|
| 1 | smallest of all: 11, swap it with 64 | [11, 25, 12, 22, 64] |
| 2 | smallest of the rest: 12, swap it with 25 | [11, 12, 25, 22, 64] |
| 3 | smallest of the rest: 22, swap it with 25 | [11, 12, 22, 25, 64] |
| 4 | smallest of the rest: 25, already in place | [11, 12, 22, 25, 64] |
The last number left must be the biggest, so 5 numbers need only 4 passes. Here is selection sort in JavaScript:
function selectionSort(arr) {
for (let i = 0; i < arr.length - 1; i++) {
let minIdx = i; // find the smallest of what is left
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIdx]) minIdx = j;
}
if (minIdx !== i) {
[arr[i], arr[minIdx]] = [arr[minIdx], arr[i]]; // at most one swap per pass
}
}
return arr;
}
console.log(selectionSort([64, 25, 12, 22, 11]).join(",")); // 11,12,22,25,64
iis the position being filled. Every number before indexiis already sorted.minIdxholds the index of the smallest number found so far. It starts atiitself.- The inner loop (
j) starts ati + 1and checks the rest. When it finds a number smaller thanarr[minIdx], the loop stores that number's index inminIdx. arr[i]andarr[minIdx]are swapped only after the inner loop is done. If the smallest number is already at positioni, no swap is needed.return arris written after the outer loop, then.join(",")joins the array's items into the text11,12,22,25,64.
How slow it is
The amount of data is called n. Selection sort always checks every number that's left, whatever the data: 5 numbers take 4 + 3 + 2 + 1 = 10 comparisons, even when the data is already sorted. So sorted data doesn't make selection sort any faster. Its comparisons are O(n²) in every case: double the data, and the time is roughly four times as long.
Its strength is the number of swaps: at most one swap per pass, so at most n - 1 swaps. That's O(n) swaps: double the data, and the number of swaps at most doubles. Bubble sort can swap up to O(n²) times. That's why selection sort fits when writing or moving data is expensive, meaning it takes a lot of time or effort.
⚠️ Four small slips in selection sort
- Swapping inside the inner loop. If you swap every time you find a smaller number, the result may still be sorted. But you make a lot of swaps, and it isn't selection sort any more. Store the index first, then swap once after the inner loop.
- Storing the value, not the index. If you only keep the smallest number itself, you don't know where it is, so you can't swap it.
minIdxstarting at 0.let minIdx = 0on every pass always points at the number at the front (index 0), which is already sorted. Start fromminIdx = i.- Forgetting
return arr. Without that line, the function returnsundefined, and.join(",")causes an error.
🎯 Bubble, selection or insertion?
This table compares selection sort with bubble sort and insertion sort. Insertion sort is the next lesson. In the last row, stable means two equal values keep their original order, for example two students with the same score stay in the order of the original list.
| Bubble sort | Selection sort | Insertion sort | |
|---|---|---|---|
| Each pass | swaps neighbours that are out of order | finds the smallest, swaps once | slides one number into the sorted left part |
| Already sorted data | O(n) with swapped |
still O(n²) | O(n) |
| Number of swaps | can be O(n²) | at most n - 1 | shifts can be O(n²) |
| Stable | yes | no | yes |
TL;DR: Selection sort sorts an array by filling positions from the left. On every pass (one run through the array), find the index of the smallest number (minIdx) in the rest of the array. Then swap that number once into position i, the position being filled. Store the index, not the value, swap after the search is done, and return arr. Its comparisons are always O(n²), even on sorted data, but it makes at most n - 1 swaps, so O(n). Selection sort isn't stable: two equal values can change their order.
⚡ Find the smallest, swap once
Write:
function selectionSort(arr) {
for (let i = 0; i < arr.length - 1; i++) {
let minIdx = i; // find the smallest of what is left
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIdx]) minIdx = j;
}
if (minIdx !== i) {
[arr[i], arr[minIdx]] = [arr[minIdx], arr[i]]; // at most one swap per pass
}
}
return arr;
}
Meaning: Selection sort fills positions from the left, and i is the position being filled. minIdx holds the index of the smallest number found so far in the rest of the array, starting at i. arr[i] is swapped with arr[minIdx] only after the inner loop is done, so there is at most one swap per pass.
⚡ Store the index, not the value
Meaning: If you only keep the smallest number itself, you don't know which index it is at, so you can't swap it. Also start from minIdx = i, not 0, so minIdx doesn't point back at a number at the front that is already sorted.
⚡ O(n²) comparisons, O(n) swaps
Guess first: [11, 12, 22, 25, 64] is already sorted. How many comparisons does selection sort make?
Still 10, that's 4 + 3 + 2 + 1, because every pass still checks every number that's left. Sorted data doesn't make selection sort any faster.
Meaning: Its comparisons are O(n²) in every case. Its strength is the number of swaps: at most one per pass, so at most n - 1 swaps, which is O(n).