AlgoFrames

Selection sort

Selection sort scans for the smallest remaining value and swaps it into place, one swap per pass. It always takes O(n²) comparisons.

Before you start: Bubble sort.

The idea

To sort cards in your hand, you can pull out the smallest card, then the next smallest, and so on.

Each pick is final: once the smallest card is in front, it never moves again. Selection sort does exactly this.

Intuition

Scan every unsorted value and remember where the smallest is. Here min ends at index 3, the value 1.

Swap 1 with the first unsorted value. The sorted part grows by one with a single swap.

Only one swap per pass is needed because the scan already knows the final value for this cell.

Complexity

Every input costs n(n - 1)/2 comparisons, so selection sort is O(n²) even on sorted input. It makes at most n - 1 swaps.

Pass k scans all n - k unsorted values no matter what they are. Few swaps make it useful when writes are expensive.

The sort works inside the array. It stores only i, min and j, so space is O(1).

Pitfalls

The swap can jump a value past an equal one. On 3a 3b 1, pass 1 swaps 3a with 1, so 3b ends up first.

Stable sorts keep equal values in input order. Selection sort is not stable because of its long-distance swaps.

Swap once, after the scan. Swapping every time a smaller value appears writes far more, here 2 swaps instead of 1.

Variations

Heap sort is selection sort with a faster scan. A heap hands over the smallest value in O(log n) instead of O(n).

A stable version slides the minimum left and shifts the others right, as insertion sort does.

Code

Pseudocode

n ← length of a
for i ← 0 to n - 2
  min ← i
  for j ← i + 1 to n - 1
    if a[j] < a[min]
      min ← j
  if min ≠ i: swap a[i] and a[min]
return a

Python

def selection_sort(a):
    n = len(a)
    for i in range(n - 1):
        min = i
        for j in range(i + 1, n):
            if a[j] < a[min]:
                min = j
        if min != i:
            a[i], a[min] = a[min], a[i]
    return a

JavaScript

function selectionSort(a) {
  const n = a.length;
  for (let i = 0; i < n - 1; i++) {
    let min = i;
    for (let j = i + 1; j < n; j++) {
      if (a[j] < a[min]) min = j;
    }
    if (min !== i) [a[i], a[min]] = [a[min], a[i]];
  }
  return a;
}

Java

static void selectionSort(int[] a) {
    int n = a.length;
    for (int i = 0; i < n - 1; i++) {
        int min = i;
        for (int j = i + 1; j < n; j++) {
            if (a[j] < a[min]) min = j;
        }
        if (min != i) { int tmp = a[i]; a[i] = a[min]; a[min] = tmp; }
    }
}

Cost at a glance

BestO(n²)
AverageO(n²)
WorstO(n²)
SpaceO(1)
Stableno
In-placeyes
Adaptiveno

Practice problems (6)

State after two passes Warm-up

Selection sort runs on [29, 10, 14, 37, 13]. Arrange the values as they stand after the first two passes.

Count comparisons Warm-up

Selection sort runs on [6, 3, 8, 1, 9, 2]. Count its comparisons, first in pass 1 and then in total.

Is selection sort stable? Standard

Selection sort runs on [3a, 3b, 1], where 3a and 3b have the same key 3. A sort is stable when equal keys keep their input order. Is selection sort stable?

Implement selection sort Standard

Sort nums in ascending order with selection sort and return it. Each pass finds the smallest unsorted value and swaps it into the first unsorted position.

The k smallest values Standard

Return the k smallest values of nums in ascending order. Use only k passes of selection sort instead of sorting the whole array.

Selection sort of pairs by key Challenge

Each pair in pairs is [key, id]. Sort the pairs by key in ascending order with a selection sort, and keep pairs with equal keys in their input order (a stable sort).

A plain swap breaks the tie order, so move the minimum into place without swapping it past equal keys.

Related topics

Next on the path: Insertion sort