About this visualization
Selection sort divides the list into a sorted part and an unsorted part. Each round it scans the unsorted part for the smallest item and swaps it to the front. It always makes the same number of comparisons but at most n − 1 swaps, which matters when writing data is expensive.
How it works
- Scan the unsorted part to find the smallest item.
- Swap it with the first item of the unsorted part.
- Grow the sorted part by one and repeat.
Worked example
Sort [64, 25, 12, 22, 11]. Round 1 finds 11 and swaps it with 64 → [11, 25, 12, 22, 64]. Round 2 finds 12 → [11, 12, 25, 22, 64]. Round 3 finds 22 → [11, 12, 22, 25, 64]. Round 4 finds 25 already in place. That is 10 comparisons and 3 swaps.
Enter these numbers in the simulator above to see every step.
Complexity and properties
| Best case | |
|---|---|
| Average case | |
| Worst case | |
| Space | |
| Stable | No |
| In-place | Yes |
Always makes at most n − 1 swaps, which helps when writes are expensive.
When to use it
- Understanding the 'find the minimum' idea behind sorting.
- Situations where the number of writes must be minimised.
- Comparing with insertion sort on nearly sorted data.
Frequently asked questions
What is the time complexity of selection sort?
for best, average and worst cases because it always scans the whole unsorted part. Space complexity is .
Is selection sort stable?
The usual swap-based version is not stable, because swapping can move an equal item past another.
How many swaps does selection sort make?
At most n − 1 swaps, one per round, which is fewer than bubble sort or insertion sort.