Post

Selection Sort in Java

Learn how Selection Sort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.

Selection Sort in Java

Introduction

Selection Sort is a simple comparison sort. It repeatedly selects the smallest value from the unsorted part of the array and swaps it to the front of that part, so the sorted part on the left grows by one value each round.

Three ideas carry the whole algorithm:

  • Sorted part: the values to the left of i are the smallest values of the array, already in their final positions.
  • Find the minimum: scan the whole unsorted part once to find the index of its smallest value.
  • Swap: exchange that smallest value with the first value of the unsorted part, at index i.

Selection Sort is easy to understand and makes very few swaps: at most $n - 1$, one per round. Its weakness is that it always scans the whole unsorted part, so it takes $O(n^2)$ comparisons even when the array is already sorted. In practice, insertion sort is the better simple sort, but Selection Sort is the basis of a much faster one: Heap Sort is Selection Sort with a heap to find the maximum quickly.

This article uses the standard Selection Sort with one swap per round: each round finds the index of the minimum first, and only then swaps once.

Performance Characteristics

Selection Sort needs almost no extra memory, and its running time doesn’t depend on the input at all: every round scans the whole unsorted part, whatever order the values are in.

Time Complexity

Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.

CaseTimeWhen it happens
Best$O(n^2)$Any input, even an array that is already sorted
Average$O(n^2)$Random or mixed input
Worst$O(n^2)$Any input: the number of comparisons is always the same

Why $n^2$? Round $i$ scans the $n - i - 1$ values after position $i$ to find the minimum. Over all rounds that adds up to $\frac{n(n-1)}{2}$ comparisons, whatever the values are.

Selection Sort makes at most $n - 1$ swaps, fewer than almost any other sort. When writing to memory is far more expensive than reading, for example on flash storage, that can matter more than the number of comparisons.

Space Complexity

Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.

PropertyValue
Space$O(1)$: only two loop variables and the index of the minimum
In placeYes
StableNo (the swap can move a value past an equal one)

Algorithm (Pseudo Code)

Selection Sort starts by looking at every value in the array to find the smallest one. It remembers where that value is, and when the scan is complete, it swaps the smallest value with the first value of the array. The smallest value is now at the front, which is exactly where it belongs, and it never moves again.

Then it does the same for the rest of the array: it finds the smallest value from the second position onwards and swaps it into the second position, and so on. Each round adds one more value to the sorted part on the left. When only one value is left in the unsorted part, it must be the largest, so the array is sorted.

1
2
3
4
5
6
7
8
9
10
11
12
sort(array):
    for i = 0 to n - 2:
        minIndex = findIndexOfMin(array, i)
        swap(array[i], array[minIndex])
    return array

findIndexOfMin(array, start):
    minIndex = start
    for j = start + 1 to n - 1:
        if array[j] < array[minIndex]:
            minIndex = j
    return minIndex

After round i, array[0 .. i] holds the i + 1 smallest values of the array, in their final sorted order.

Selection Sort is not stable, even though the comparison is strict. With [2a, 2b, 1], the first round swaps 1 with 2a, giving [1, 2b, 2a]: the two equal values have changed order. The comparison only decides which value is selected; it is the long-distance swap that breaks stability.

Visualization

The visualization below follows the Java code line by line, starting with the values 0 to 9 in shuffled order.

Each step shows the array, the pointers and the line of code that is running, with a short explanation of what just happened:

  • Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
  • Play: press Play to run the steps automatically, and press it again to pause.
  • Shuffle: press the shuffle button to start again with a new random order.
  • Pointers: I is i in sort, the position being filled. J is the value being checked by the scan in findIndexOfMin, and M is minIndex, the smallest value found so far.
  • Colours: the smallest value found so far is amber, the two values being swapped are salmon, and values in their final position turn green.
  • Boundary: the gray bar marks where the unsorted part starts.
smallest so far swap final position I = i J = scan M = minIndex

Java Code

The implementation is a SelectionSort class with one public method, sort, which fills the array from left to right, and one private method, findIndexOfMin, which scans the unsorted part for its smallest value. Two small helpers, less and swap, live in a separate SortUtils class.

The complete code is in the algorithm-examples repository on GitHub: SelectionSort.java, with the helpers in SortUtils.java.

sort

1
2
3
4
5
6
7
8
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
    for (int i = 0; i < array.length - 1; i++) {
        final int minIndex = findIndexOfMin(array, i);
        SortUtils.swap(array, i, minIndex);
    }
    return array;
}

sort is the entry point. It accepts an array of any Comparable type, such as Integer or String, and sorts it in place. For each position i from the left, it asks findIndexOfMin where the smallest value of array[i ..] is, and swaps that value into position i. It returns the same array, now sorted.

Two details are worth noticing:

  • The loop stops at array.length - 1, not array.length. When every other position is filled, the one value left at the end must be the largest, so a last round would have nothing to compare it with.
  • When the smallest value is already at i, minIndex equals i, and swap does nothing. There is no need for a separate check in sort.

findIndexOfMin

1
2
3
4
5
6
7
8
9
private static <T extends Comparable<T>> int findIndexOfMin(T[] array, final int startIndex) {
    int minIndex = startIndex;
    for (int i = startIndex + 1; i < array.length; i++) {
        if (SortUtils.less(array[i], array[minIndex])) {
            minIndex = i;
        }
    }
    return minIndex;
}

findIndexOfMin scans the unsorted part once. It starts by assuming the value at startIndex is the smallest, then checks every later value and remembers the index of any value that is smaller. It returns an index, not the value, because sort needs to know where to swap from.

Its loop variable is also called i, but it is a different variable from the i in sort: here it walks through the unsorted part, while in sort it marks the position being filled. In the visualization, the scan is shown as J to keep the two apart. Because the comparison is strict, the scan keeps the first of several equal minimums.

less and swap

1
2
3
4
5
6
7
8
9
10
11
public static <T extends Comparable<T>> boolean less(T firstElement, T secondElement) {
    return firstElement.compareTo(secondElement) < 0;
}

public static <T> void swap(T[] array, int i, int j) {
    if (i != j) {
        final T temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

These two helpers from SortUtils keep the sorting code easy to read. less returns true when the first element is smaller than the second, using compareTo, so the algorithm works for any type that implements Comparable. swap exchanges two elements, and skips the work when both indices are the same, which happens whenever a value is already in its place.

Running it

1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new SelectionSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Create a SelectionSort, pass it an array, and the same array comes back sorted. The array holds Integer, not int, because the method works with Comparable objects.

Summary

  • Selection Sort is a simple comparison sort: each round selects the smallest remaining value and swaps it to the front of the unsorted part.
  • This implementation finds the index of the minimum with findIndexOfMin first, and then makes exactly one swap per round.
  • After round i, array[0 .. i] holds the smallest values in their final order.
  • It always runs in $O(n^2)$, even on sorted input, with only $O(1)$ extra space and at most $n - 1$ swaps.
  • It sorts in place but is not stable. Insertion sort is usually the better simple sort; Heap Sort keeps the same idea of selecting the extreme value, but finds it in $O(\log n)$ with a heap.
This post is licensed under CC BY 4.0 by the author.