Skip to content
Part IA Lent Term

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 i=0i = 0 to n2n-2:

  1. Find the index jj of the minimum element in A[in1]A[i \dots n-1].
  2. Swap A[i]A[i] with A[j]A[j].

Selection sort: repeatedly select the minimum of what remains and place it at the front

Invariant

At the start of iteration ii, the subarray A[0i1]A[0 \dots i-1] contains the ii smallest elements of the original array, in sorted order. The remaining elements A[in1]A[i \dots n-1] are unsorted.

  • Initialisation (i=0i=0): A[01]A[0 \dots -1] is empty, trivially sorted.
  • Maintenance: Appending the next minimum extends the sorted prefix correctly.
  • Termination (i=n1i=n-1): A[0n2]A[0 \dots n-2] sorted plus the final element (the largest) at n1n-1 completes the sort.

Complexity: Always Θ(n2)\Theta(n^2) Comparisons

Selection Sort performs no early exit. For each ii, finding the minimum in the remaining nin-i elements requires ni1n-i-1 comparisons:

i=0n2(ni1)=k=1n1k=n(n1)2=Θ(n2)\sum_{i=0}^{n-2} (n-i-1) = \sum_{k=1}^{n-1} k = \frac{n(n-1)}{2} = \Theta(n^2)

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 Θ(n2)\Theta(n^2) comparisons, making it data-insensitive.

Swaps: Only Θ(n)\Theta(n)

Each iteration performs exactly one swap, and there are n1n-1 iterations (the last element is automatically in place). Thus the total number of swaps is:

Swaps=n1=Θ(n)\text{Swaps} = n-1 = \Theta(n)

A lower bound theorem shows that any sorting algorithm must perform Ω(n)\Omega(n) swaps in the worst case (consider the input [2,3,,n,1][2, 3, \ldots, n, 1] where every item starts in the wrong place, and each swap touches two items). Selection Sort achieves this lower bound exactly.

Properties

PropertyValue
ComparisonsAlways Θ(n2)\Theta(n^2)
SwapsΘ(n)\Theta(n) (optimal)
In-placeYes, O(1)O(1) space
StableNo — the swap can jump over equal elements
Data-sensitiveNo — same work regardless of input

Why Stability Fails

Consider [5a,5b,2][5_a, 5_b, 2]. Selection Sort finds 2 as the minimum and swaps it with 5a5_a, producing [2,5b,5a][2, 5_b, 5_a]. The relative order of 5a5_a and 5b5_b 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 Θ(n)\Theta(n) writes total. This is optimal for sorting algorithms.

Summary

AspectDetail
StrategyRepeatedly select minimum, swap to front
ComparisonsΘ(n2)\Theta(n^2), always
SwapsΘ(n)\Theta(n), optimal
In-placeYes
StableNo
Use caseExpensive writes, cheap comparisons
Lower bound achievedΩ(n)\Omega(n) swaps