Selection Sort Algorithm
Selection sort does exactly what the name says. Scan the unsorted portion, select the smallest element, swap it into position. Repeat.
19 Mar 2024 · 2 min read

Selection sort does exactly what the name says. Scan the unsorted portion, select the smallest element, swap it into position. Repeat.
It's the algorithm you'd naturally invent if someone handed you a deck of cards and said "sort these." Look through all of them, find the smallest, put it first. Find the next smallest, put it second. And so on.
The intuition
Divide the array into two regions: sorted (left) and unsorted (right). Each pass finds the minimum in the unsorted region and swaps it with the first unsorted element.
function selectionSort(arr) {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
let minIndex = i;
for (let j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex !== i) {
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
}
return arr;
}
Complexity
- Time: O(n²) — always, even if the array is already sorted. The inner loop runs regardless.
- Space: O(1) — sorts in-place.
When to use it (and when not to)
Selection sort has one advantage over bubble sort: it minimizes the number of swaps (at most n-1). If swaps are expensive — say you're moving large records on disk — that matters.
But for almost everything else, it's too slow. Merge sort and quicksort run in O(n log n). Use selection sort to understand sorting concepts. Use something else in production.
Ehsan Gazar helps software engineers take LLM and agent systems from demo to production. He writes about building LLM systems that hold up in production: evals, tracing, RAG, agent architecture and cost control. He teaches the Senior to Staff AI Engineer cohort on Maven, where engineers learn to design and defend these systems.
Forward Deployed AI Engineering: From Customer Problem to Production Value
A live Maven cohort for engineers: 10 live 90-minute sessions taking one AI engagement from customer problem to production, ending with eight artefacts and a working slice in your own repo.
January cohort starts Tue 12 Jan 2027, Tue & Thu 6:30pm London. Enrolling now, 20 seats, $1,800.
View the live cohort