Selection Sort
Overview
Selection sort works by iterating upward through an array, swapping the value in the current position with the smallest value in the remainder of the array.
| Property | Value |
|---|---|
| Best Case | |
| Worst Case | |
| Avg. Case | |
| Aux. Memory | |
| Stable | No |
| Adaptive | No |
| Visualization | ![]() |
Loop Invariant
Selection sort has loop invariant
A[0:i-1]is a sorted array of theileast elements ofA.
- Initialization
- When
i = 0,A[0:-1]is an empty array. This trivially satisfies.
- When
- Maintenance
- Suppose
holds for some 0 ≤ i < n - 1. ThenA[0:i-1]is a sorted array of theileast elements ofA. Our inner loop then finds the smallest element inA[i:n]and swaps it withA[i]. ThereforeA[0:i]is a sorted array of thei + 1least elements ofA. At the end of the iteration,iis incremented meaningA[0:i-1]still satisfies.
- Suppose
- Termination
- On termination,
i = n - 1andA[0:n-2]are then - 1least elements ofAin sorted order. But, by exhaustion,A[n-1]must be the largest element meaningA[0:n-1], the entire array, is in sorted order.
- On termination,
