Selection Sort Algorithm Explained
Selection sort repeatedly finds the smallest remaining element and moves it to the front of the unsorted portion of the list.
Published November 15, 2026
Selection sort repeatedly finds the smallest remaining item and swaps it into the next position of the sorted part. It always does O(n²) comparisons but makes at most n−1 swaps.
The concept
Scan the unsorted part for the minimum, swap it with the first unsorted element, then move the boundary one step right.
Its performance does not depend on the input order, and it is not stable. It is handy only when writes are very expensive.
Selecting minimums
- [64, 25, 12, 22] → min is 12, swap with 64
- [12, 25, 64, 22] → min of rest is 22, swap with 25
- [12, 22, 64, 25] → min is 25, swap with 64
- [12, 22, 25, 64] sorted
Practical examples
JavaScript
function selection(a) {
a = [...a]
for (let i = 0; i < a.length - 1; i++) {
let m = i
for (let j = i + 1; j < a.length; j++) if (a[j] < a[m]) m = j
;[a[i], a[m]] = [a[m], a[i]]
}
return a
}Python
def selection(a):
for i in range(len(a)):
m = min(range(i, len(a)), key=a.__getitem__)
a[i], a[m] = a[m], a[i]
return aComplexity
always O(n²) comparisons · O(n) swaps · O(1) space · not stableCommon mistakes
- Expecting best-case speedups on sorted input.
- Assuming it is stable.
- Using it on large lists.
Key takeaways
- Pick the min, swap into place.
- Few swaps, many comparisons.
- Not stable.
FAQ
When is it useful?
When swaps are costly, such as writing to flash memory.
Is it faster than bubble sort?
Usually yes, thanks to fewer swaps.