Selection Sort
Algorithm
Selection Sort repeatedly finds the minimum element of the unsorted suffix and swaps it with the first unsorted position. For 0-indexed arrays:
For to :
- Find the index of the minimum element in .
- Swap with .
Invariant
At the start of iteration , the subarray contains the smallest elements of the original array, in sorted order. The remaining elements are unsorted.
- Initialisation (): is empty, trivially sorted.
- Maintenance: Appending the next minimum extends the sorted prefix correctly.
- Termination (): sorted plus the final element (the largest) at completes the sort.
Complexity: Always Comparisons
Selection Sort performs no early exit. For each , finding the minimum in the remaining elements requires comparisons:
There is no best-case scenario that reduces comparisons; even if the array is already sorted, every element is still compared. The running time is always comparisons, making it data-insensitive.
Swaps: Only
Each iteration performs exactly one swap, and there are iterations (the last element is automatically in place). Thus the total number of swaps is:
A lower bound theorem shows that any sorting algorithm must perform swaps in the worst case (consider the input where every item starts in the wrong place, and each swap touches two items). Selection Sort achieves this lower bound exactly.
Properties
| Property | Value |
|---|---|
| Comparisons | Always |
| Swaps | (optimal) |
| In-place | Yes, space |
| Stable | No — the swap can jump over equal elements |
| Data-sensitive | No — same work regardless of input |
Why Stability Fails
Consider . Selection Sort finds 2 as the minimum and swaps it with , producing . The relative order of and is reversed, so the sort is not stable.
When to Use
Selection Sort is effective when writes are expensive but comparisons are cheap. Each element is written at most twice (once when swapped into the sorted region, once when displaced from the unsorted region), giving writes total. This is optimal for sorting algorithms.
Summary
| Aspect | Detail |
|---|---|
| Strategy | Repeatedly select minimum, swap to front |
| Comparisons | , always |
| Swaps | , optimal |
| In-place | Yes |
| Stable | No |
| Use case | Expensive writes, cheap comparisons |
| Lower bound achieved | swaps |