Lesson 33 · Core algorithms

Selection Sort: Scanning, Swapping and Cost

Find the smallest value in the unsorted part, swap it to the front of that part, and move the boundary one place right. After n − 1 rounds the array is sorted.

Selection Sort: Scanning, Swapping and Cost concept diagramA visual explanation of the layout and operations shown in this lesson.scan the unsorted part for its smallest value, then place it290101142373124minimum = 10swap into position 0at most n − 1 swaps; skip the swap when the minimum is already in place
1

How Selection Sort Works

  1. Set the boundary i = 0
  2. Scan positions i to n − 1 and remember the index of the smallest value
  3. If that index is not i, swap the two values
  4. Move the boundary to i + 1 and repeat until i = n − 1

Selection sort keeps the array in two parts: a sorted part on the left and an unsorted part on the right. Each round selects the smallest unsorted value and swaps it to the front of the unsorted part. The sorted part grows by one, and every value in it is already in its final place.

On [29, 10, 14, 37, 12] the rounds are: 10 swaps with 29, 12 swaps with 29, 14 is already in place, 29 swaps with 37. Four rounds for five values; the last value is right by elimination.

  • Invariant: a[0..i−1] is sorted and final
  • The scan only reads; the one swap is the only write in a round
2

Selection Sort Time Complexity

Round 1 compares n − 1 pairs, round 2 compares n − 2, and so on down to 1. The total is n(n − 1)/2 comparisons, for every input. You cannot know a value is the smallest without comparing it with all the others, so there is no early exit: sorted input costs exactly what reversed input costs.

  • Time: Θ(n²) in the best, average and worst case
  • Space: O(1), sorted in place

Swaps are different. Each round makes at most one, so the total is at most n − 1, and sorted input needs none. Reversed input of five values needs only two.

  • Comparisons: n(n − 1)/2 always, 10 for n = 5, about 50 million for n = 10,000
  • Swaps: at most n − 1
3

Why Selection Sort Is Not Stable

A sort is stable if equal keys keep their original order. The usual selection sort is not, because its swap can move a value a long way in one step.

Take [4a, 4b, 1], where 4a and 4b have the same key. Round 1 swaps 1 with 4a, giving [1, 4b, 4a]. Round 2 sees two equal values and makes no swap. The output is sorted, but 4b now comes before 4a. This matters when you sort records by one field after another, as explained in stable vs unstable sorting.

A stable version exists: instead of swapping, take the minimum out, shift the values between right by one, and insert it. That keeps equal keys in order, but each round can now make n writes, which throws away selection sort's main advantage. If you need a stable simple sort, insertion sort is stable and usually faster; for large inputs use merge sort.

  • The swap can jump a value over an equal one
  • The shifting version is stable but makes O(n²) writes
Key reference

Terms, operations, and practical uses

The idea

  • Sorted prefixThe left part of the array. It holds the smallest values seen so far, each already in its final place.
  • Unsorted suffixThe right part, still to be scanned. Each round removes its smallest value.
  • Minimum indexThe scan remembers where the smallest value is, not the value itself, so it can swap afterwards.

Cost

  • n(n − 1)/2 comparisonsThe same on every input, because each scan must look at every remaining value.
  • At most n − 1 swapsOne per round at most, and none when the minimum is already in place.
  • In placeOnly a few index variables: O(1) extra memory.

Limits

  • Not stableA long swap can move a value past an equal one, as [4a, 4b, 1] becoming [1, 4b, 4a] shows.
  • Not adaptiveSorted input is no faster; insertion sort and bubble sort with an early exit are.
  • Write-lightThe reason to use it: far fewer writes than bubble or insertion sort.
Implementation

Code in Python, C++ and Java

def selection_sort(values):
    n = len(values)
    swaps = 0
    for i in range(n - 1):
        smallest = i
        for j in range(i + 1, n):
            if values[j] < values[smallest]:
                smallest = j
        if smallest != i:
            values[i], values[smallest] = values[smallest], values[i]
            swaps += 1
    return swaps


for data in [[29, 10, 14, 37, 12], [37, 29, 14, 12, 10]]:
    before = " ".join(map(str, data))
    swaps = selection_sort(data)
    print(before, "->", " ".join(map(str, data)), "| swaps:", swaps)
#include <iostream>
#include <utility>
#include <vector>
using namespace std;

int selectionSort(vector<int>& values) {
    int n = values.size(), swaps = 0;
    for (int i = 0; i < n - 1; i++) {
        int smallest = i;
        for (int j = i + 1; j < n; j++)
            if (values[j] < values[smallest]) smallest = j;
        if (smallest != i) {
            swap(values[i], values[smallest]);
            swaps++;
        }
    }
    return swaps;
}

void print(const vector<int>& v) {
    for (size_t i = 0; i < v.size(); i++) cout << (i ? " " : "") << v[i];
}

int main() {
    vector<vector<int>> inputs = {{29, 10, 14, 37, 12}, {37, 29, 14, 12, 10}};
    for (vector<int>& data : inputs) {
        print(data);
        int swaps = selectionSort(data);
        cout << " -> ";
        print(data);
        cout << " | swaps: " << swaps << "\n";
    }
}
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    static int selectionSort(int[] values) {
        int n = values.length, swaps = 0;
        for (int i = 0; i < n - 1; i++) {
            int smallest = i;
            for (int j = i + 1; j < n; j++)
                if (values[j] < values[smallest]) smallest = j;
            if (smallest != i) {
                int tmp = values[i];
                values[i] = values[smallest];
                values[smallest] = tmp;
                swaps++;
            }
        }
        return swaps;
    }

    static String show(int[] v) {
        return Arrays.stream(v).mapToObj(String::valueOf).collect(Collectors.joining(" "));
    }

    public static void main(String[] args) {
        int[][] inputs = {{29, 10, 14, 37, 12}, {37, 29, 14, 12, 10}};
        for (int[] data : inputs) {
            String before = show(data);
            int swaps = selectionSort(data);
            System.out.println(before + " -> " + show(data) + " | swaps: " + swaps);
        }
    }
}
Watch it run

Step through it

Running on [29, 10, 14, 37, 12], then sorted, reversed and [4a, 4b, 1]

[29, 10, 14, 37, 12]290101142373124comparisons 0 · swaps 0invariant: everything left of the boundary is sorted and already in its final place5 values, 4 rounds
Step 1

Start: the whole array is unsorted

Selection sort splits the array into a sorted part on the left and an unsorted part on the right. At the start the sorted part is empty. Each round finds the smallest unsorted value and swaps it to the front of the unsorted part, so the sorted part grows by one.

Output
1 / 12
4

Selection Sort vs Bubble Sort and Insertion Sort

All three simple sorts are O(n²) on average. They differ in how many writes they make and whether sorted input is fast. Bubble sort swaps neighbours every time it finds a pair out of order, so it makes one swap per inversion: 10 on reversed input of five values, against selection sort's 2. Insertion sort shifts values instead of swapping and stops early on nearly sorted input.

The three simple sorts side by side
Selection sortBubble sortInsertion sort
Comparisons, sorted inputn(n − 1)/2n − 1 (with early exit)n − 1
Comparisons, worst casen(n − 1)/2n(n − 1)/2n(n − 1)/2
Swaps or shifts, worst casen − 1 swapsn(n − 1)/2 swapsn(n − 1)/2 shifts
StableNoYesYes
  • Choose selection sort when writes are much costlier than reads, such as flash memory or EEPROM
  • Otherwise insertion sort is usually the better simple sort
5

Edge Cases and Variants

Selection sort handles small and odd inputs without special code, and a few variants change its trade-offs.

  • Empty array or one value: the outer loop runs zero times
  • All values equal: still n(n − 1)/2 comparisons, but no swaps because the test is strictly less than
  • Skip the swap when the minimum is already at the boundary; swapping a value with itself is wasted writes
  • Double selection: find the minimum and maximum in one scan and place both, halving the rounds but not the comparisons
  • Heap sort is selection sort with a heap: the minimum is found in O(log n), giving O(n log n) (heap sort)