Repeatedly select the minimum element from the unsorted portion and place it at the beginning.
Selection sort divides the array into a sorted prefix and an unsorted suffix. At each step, it selects the smallest element from the unsorted portion and swaps it into the next position of the sorted prefix.
Unlike bubble-based methods, it performs a fixed number of swaps, which can be useful when swaps are expensive.
Problem
Given a sequence of length , reorder it such that
Algorithm
For each position , find the minimum element in the range and swap it with .
selection_sort(A):
n = length(A)
for i from 0 to n - 1:
min_index = i
for j from i + 1 to n - 1:
if A[j] < A[min_index]:
min_index = j
swap(A[i], A[min_index])Example
Let
Step 1:
Minimum in is
→ [11, 25, 12, 22, 64]
Step 2:
Minimum in is
→ [11, 12, 25, 22, 64]
Step 3:
Minimum in is
→ [11, 12, 22, 25, 64]
Sorted result:
Correctness
After iteration , the smallest element among indices through is placed at position . This maintains the invariant that the prefix is sorted and contains the smallest elements. Repeating this for all positions yields a fully sorted array.
Complexity
| case | comparisons | time |
|---|---|---|
| best | ||
| worst | ||
| average |
Space complexity:
Properties
- in-place
- not stable in standard form
- minimizes number of swaps
When to Use
Selection sort is useful when swap operations are expensive but comparisons are cheap. It guarantees at most swaps, which can be advantageous in constrained environments.
Implementation
def selection_sort(a):
n = len(a)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
if a[j] < a[min_idx]:
min_idx = j
a[i], a[min_idx] = a[min_idx], a[i]
return afunc SelectionSort[T constraints.Ordered](a []T) {
n := len(a)
for i := 0; i < n; i++ {
minIdx := i
for j := i + 1; j < n; j++ {
if a[j] < a[minIdx] {
minIdx = j
}
}
a[i], a[minIdx] = a[minIdx], a[i]
}
}