Data Structures · Sorting

Selection Sort

🔢 The array a[] (settled part / scan)

settled positionscanning (j)current minimum / swapping
result

🧾 Pass-by-pass record

💬 Current step

💻 The algorithm (courseware-style C++)

Yellow = the line being executed. The recipe: scan for the minimum → one swap to the front of the unsorted part.

📄 Key points

1Each pass scans the unsorted part: j = i+1 … n−1
2Use min to remember where the smallest element is
3Only one swap at the end of the pass (and only if min != i)
4Comparisons are always n(n−1)/2; at most n−1 swaps
How is it different from bubble sort? Bubble compares neighbours and swaps constantly; selection scans for the minimum and swaps once per pass — the same number of comparisons, far fewer swaps.
Complexity: comparisons are always n(n−1)/2 → time O(n²) (sorted or not); swaps ≤ n−1; space O(1).
Why is it not stable? The swap is a long-distance one: with [3a, 3b, 1] the first pass exchanges 1 with 3a, so the two 3s change order.
When to use it: when elements are large (moving or copying them is expensive) and comparisons are cheap.
Speed
Shortcuts: Space play/pause · ←→ step · R reset · E result