COMPARISON SORTS
Selection Sort, visualised
Selection sort finds the minimum of the unsorted part and swaps it with the first unsorted position, repeating until done. Values become fixed from left to right.
Run Selection Sort in the visualizer →
Opens the Sorting Cinema visualizer with 16 elements in English.
How it works
- Treat the first unsorted element as the current minimum.
- Compare it with each remaining element and update the minimum position when a smaller value appears.
- After the scan, swap the minimum with the first unsorted element (no swap if it is already there).
- Move the boundary one step right and repeat.
Complexity and stability
- Best
- O(n²)
- Average
- O(n²)
- Worst
- O(n²)
- Extra space
- O(1)
- Stability
- Usually unstable
It always scans the whole remaining range for the minimum, so it makes O(n²) comparisons regardless of input order. It performs at most one swap per pass.
Source of facts: Complexity follows the learning guide's comparison table and text, and this app's implementation.
Trace on a small array
The first operations on the input [5, 2, 4, 1, 3], following the same steps as the app.
| # | Operation | Array after |
|---|---|---|
| 1 | Compare [0]=5 and [1]=2 | [5, 2, 4, 1, 3] |
| 2 | Compare [1]=2 and [2]=4 | [5, 2, 4, 1, 3] |
| 3 | Compare [1]=2 and [3]=1 | [5, 2, 4, 1, 3] |
| 4 | Compare [3]=1 and [4]=3 | [5, 2, 4, 1, 3] |
| 5 | Swap [0]=5 and [3]=1 | [1, 2, 4, 5, 3] |
| 6 | Compare [1]=2 and [2]=4 | [1, 2, 4, 5, 3] |
| 7 | Compare [1]=2 and [3]=5 | [1, 2, 4, 5, 3] |
| 8 | Compare [1]=2 and [4]=3 | [1, 2, 4, 5, 3] |
…and so on. In this trace, 13 compare / swap / write operations in total produce [1, 2, 3, 4, 5].
Suitable inputs and caveats
- Shows a sort with few swaps (at most one per pass).
- Sorted input does not reduce the number of comparisons.
- Because it swaps with a distant position, equal values can change order (usually unstable).
FAQ
How is selection sort different from bubble sort?
Both make O(n²) comparisons, but selection sort swaps once after finding the minimum, while bubble sort swaps neighbours many times.
Is selection sort stable?
Usually not. Swapping the minimum into a distant front position can change the original order of equal values.