Selection Sort's superpower: fewest swaps of any simple sorting algorithm — at most n-1 total. In systems where writes are expensive, this matters.
🧠 The Core Idea
Every pass: scan the unsorted region, find the minimum, swap it to the front.
Analogy: Sorting 30 answer sheets by roll number. Scan all, find Roll No. 1, pull it. Scan remaining, find Roll No. 2. Repeat.
📋 Example: [64, 25, 12, 22, 11]
| Pass | Min | Result |
|---|---|---|
| 1 | 11 | [11, 25, 12, 22, 64] |
| 2 | 12 | [11, 12, 25, 22, 64] |
| 3 | 22 | [11, 12, 22, 25, 64] |
| 4 | 25 | [11, 12, 22, 25, 64] ✅ |
5 elements → 4 passes → only 2 actual swaps.
💻 JavaScript
function selectionSort(arr) {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
let minIdx = i;
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) minIdx = j;
}
if (minIdx !== i) [arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];
}
return arr;
}
⏱ Complexity
| Case | Time | Space | Stable | Max Swaps |
|---|---|---|---|---|
| All cases | O(n²) | O(1) | ❌ | n-1 |
🆚 vs Bubble Sort
| Factor | Selection | Bubble |
|---|---|---|
| Swaps | n-1 max ✅ | Up to n²/2 ❌ |
| Stable | ❌ No | ✅ Yes |
Part 8 of the Bitveen DSA Series. Originally published at bitveen.com
Top comments (0)