Algorithm · Sorting and selection · Θ(n²) comparisons, at most n − 1 swaps

Selection sort

Find the minimum of the unsorted part and swap it to the front. Θ(n²) comparisons on every input, at most n − 1 swaps, not stable.

The full derivation, edge cases and exercises are in the lesson Bubble, selection and insertion sort. Open it full width in the playground.

On this page
  1. The idea
  2. Steps
  3. Invariants
  4. Complexity
  5. When to use it
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

Selection sort always scans the whole unsorted part, so it cannot benefit from sorted input. Its one strength is the small number of writes: at most one swap per position, which mattered when writes were expensive.

Steps

  1. For each position i, find the index of the smallest element in a[i … n − 1].
  2. Swap it into position i.

Invariants

What holds at every step; the correctness argument rests on these.

  • After step i, a[0 … i] holds the i + 1 smallest elements in sorted order.
  • A long-distance swap can jump an element past an equal one, so the sort is not stable.

Complexity

Selection sort complexity
CaseTimeExtra spaceNotes
All casesΘ(n²) comparisonsO(1)At most n − 1 swaps.

When to use it

Use it when

  • Writes are far more expensive than reads, and n is small.

Avoid it when

  • Stability matters, or n is more than a few dozen.

Step through it

The interactive lab for selection sort: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

Selection sort in four languages, each checked against one shared fixture that pins down the exact (unstable) order of equal keys, and 500 random inputs whose keys are compared with the language's built-in sort.

namespace Bekadan.Dsa.Examples.Sorting;
 
/// <summary>
/// Selection sort: in place, not stable. Always n(n - 1)/2 comparisons,
/// at most n - 1 swaps.
/// </summary>
public static class SelectionSort
{
    public static void Sort<T>(T[] items, Comparison<T> compare)
    {
        for (int i = 0; i < items.Length - 1; i++)
        {
            int minIndex = i; // smallest of items[i..] seen so far
            for (int j = i + 1; j < items.Length; j++)
            {
                if (compare(items[j], items[minIndex]) < 0) // strictly smaller: the first minimum wins ties
                {
                    minIndex = j;
                }
            }
            if (minIndex != i)
                (items[i], items[minIndex]) = (items[minIndex], items[i]); // can jump over equal items: not stable
        }
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Sorting/SelectionSort.cs

"""Selection sort: in place, not stable.
 
Always n(n - 1)/2 comparisons and at most n - 1 swaps.
"""
 
from collections.abc import Callable
from typing import Any
 
 
def _identity(item: Any) -> Any:
    return item
 
 
def selection_sort(items: list[Any], key: Callable[[Any], Any] = _identity) -> None:
    for i in range(len(items) - 1):
        min_index = i  # smallest of items[i:] seen so far
        for j in range(i + 1, len(items)):
            if key(items[j]) < key(items[min_index]):  # strictly smaller: the first minimum wins ties
                min_index = j
        if min_index != i:
            items[i], items[min_index] = items[min_index], items[i]  # can jump over equal items: not stable

Tested on CPython 3.14.0 · examples/python/dsa_examples/selection_sort.py

package dev.bekadan.dsa.sorting;
 
import java.util.Comparator;
 
/**
 * Selection sort: in place, not stable. Always n(n - 1)/2 comparisons,
 * at most n - 1 swaps.
 */
public final class SelectionSort {
    private SelectionSort() {
    }
 
    public static <T> void sort(T[] items, Comparator<? super T> comparator) {
        for (int i = 0; i < items.length - 1; i++) {
            int minIndex = i; // smallest of items[i..] seen so far
            for (int j = i + 1; j < items.length; j++) {
                if (comparator.compare(items[j], items[minIndex]) < 0) { // strictly smaller: the first minimum wins ties
                    minIndex = j;
                }
            }
            if (minIndex != i) { // can jump over equal items: not stable
                T tmp = items[i];
                items[i] = items[minIndex];
                items[minIndex] = tmp;
            }
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/sorting/SelectionSort.java

#pragma once
 
#include <cstddef>
#include <functional>
#include <span>
#include <utility>
 
namespace bekadan::dsa {
 
// Selection sort: in place, not stable. Always n(n - 1)/2 comparisons,
// at most n - 1 swaps.
 
template <typename T, typename Less = std::less<>>
void selection_sort(std::span<T> items, Less less = {}) {
    for (std::size_t i = 0; i + 1 < items.size(); ++i) {
        std::size_t min_index = i;  // smallest of items[i..] seen so far
        for (std::size_t j = i + 1; j < items.size(); ++j) {
            if (less(items[j], items[min_index])) {  // strictly smaller: the first minimum wins ties
                min_index = j;
            }
        }
        if (min_index != i)
            std::swap(items[i], items[min_index]);  // can jump over equal items: not stable
    }
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/selection_sort.hpp

Learn more

Data structures it uses

Problems, patterns and exercises

References