Overview & Concept
Selection Sort is an in-place comparison sort that divides the array into a sorted sublist at the front and an unsorted sublist at the rear. It repeatedly finds the minimum element from the unsorted sublist and swaps it with the first unsorted element.
How It Works
Partitioning: Array is divided into sorted left prefix and unsorted right suffix.
Minimum Scanning: Scans the entire unsorted region to find the index of the absolute minimum value.
Single Swap per Pass: Exactly one swap is performed per outer iteration.
Deterministic O(n²): Performs the exact same number of comparisons regardless of initial array ordering.
Step-by-Step Execution
Asymptotic Complexity Analysis
| Metric | Best Case | Average Case | Worst Case | Space Complexity |
|---|---|---|---|---|
| Complexity Bound | O(n²) | O(n²) | O(n²) | O(1) |
| Explanation | Optimal input arrangement minimizing operations. | Expected time for uniformly distributed randomized inputs. | Adversarial degenerate conditions requiring full traversal. | Auxiliary memory allocated beyond original input size. |
Pseudocode & Invariants
procedure selectionSort(A):
n = length(A)
for i = 0 to n - 2:
minIdx = i
for j = i + 1 to n - 1:
if A[j] < A[minIdx]: minIdx = j
end for
if minIdx != i: swap(A[i], A[minIdx])
mark A[i] as sorted
return A- Prefix Sortedness: Elements A[0..i-1] are sorted and all smaller than every element in A[i..n-1].
Advantages & Disadvantages
Key Advantages
- •Minimizes writes: performs at most O(n) memory swap operations (useful when writes are expensive, like flash memory).
- •In-place sorting with O(1) auxiliary memory.
Trade-offs & Limitations
- •Strictly O(n²) comparisons even when input is already sorted.
- •Unstable in its standard implementation.
Real-World Applications
EEPROM / Flash Memory Sorting
Writing to flash wears out memory cells; Selection Sort minimizes total write cycles.
Decision Guide: When to Use
Ideal Scenarios
- ✓When memory write operations are significantly more costly than memory read comparisons.
Consider Alternatives When
- ✕When sorting large datasets or when stability is required.
Explore Related Algorithms
Compare trade-offs and complexity across complementary tools in AlgoViz.