level 3 · Sorting
Selection Sort
Find the smallest. Put it in front. Repeat.
what is it
Start here
Selection sort does exactly what you'd do with a hand of cards spread on a table: scan for the smallest one, pull it out, put it at the front. Then scan the rest for the next smallest.
It scans a lot but moves almost nothing. Every pass looks at every remaining item, but it performs at most one swap. If you were sorting heavy physical objects, this is the algorithm you'd want — looking is cheap, lifting is not.
The catch: it never gets to leave early. Even on a perfectly sorted list, it still scans everything to *prove* each item is the smallest. It cannot take a hint.
real-life analogy
Picture it
You look at everyone left, decide who is smallest, and pull them to the front of the line. You looked at everybody to make that one decision — but you only moved one person. Then you do it again with whoever is left.
interactive visualization
Watch it run
Type numbers separated by spaces. Count how few swaps it makes.
- 8
- 3
- 5
- 1
- 9
- 2
- 7
Selection sort hunts for the smallest value in what's left, then puts it where it belongs. One swap per pass — no more.
step 01/47
- comparing
- moving
- in final place
space · play ← → · step
| 1 | function selectionSort(a) { |
| 2 | for (let i = 0; i < a.length - 1; i++) { |
| 3 | let min = i; |
| 4 | for (let j = i + 1; j < a.length; j++) { |
| 5 | if (a[j] < a[min]) { |
| 6 | min = j; |
| 7 | } |
| 8 | } |
| 9 | if (min !== i) { |
| 10 | [a[i], a[min]] = [a[min], a[i]]; |
| 11 | } |
| 12 | } |
| 13 | return a; |
| 14 | } |
variables right now
Nothing in play yet — press play.
the dry run · every step, in words
47 stepscomplexity
What it costs
- best case
- O(n²)
- average
- O(n²)
- worst case
- O(n²)
- extra memory
- O(1)
Always n²/2 comparisons — best case, worst case, sorted, shuffled, it makes no difference. But at most n−1 swaps ever, which is the fewest of any simple sort.
- O(1)
- O(log n)
- O(n)
- O(n log n)
- O(n²) · this one
common mistakes
Common traps
Swapping every time you find a smaller value.
Only remember *where* the smallest is. Swap once, at the end of the pass. Swapping as you go throws away the algorithm's one advantage.
Expecting it to be faster on sorted input.
It isn't. Selection sort has no early exit — it must scan the whole remainder to know what the minimum is. Same cost, always.
Starting the inner scan at index 0 each pass.
Start at i + 1. Everything before i is already finished and re-scanning it is pure waste.
quiz
Check yourself
Three questions. Get them all right to finish the lesson.
+50 XP01How many swaps does selection sort make on a list of 10 items?
02Selection sort on an already-sorted list of 100 items does how many comparisons?
03When would selection sort genuinely be the right choice?
practice
Solve it on LeetCode
You've seen it run — now write it yourself. These are real LeetCode problems that use exactly this idea, from gentlest to toughest.