Selection Sort
Sort an array by finding the smallest value that is still out of place and swapping it to the front, one position at a time.
Sort an array of integers arrarr
Example
Output: [11, 12, 22, 25, 64]
The Idea
Say five numbered cards lie in a row on a table: 64, 25, 12, 22 and 11. A simple way to put them in order is to look along the row for the lowest card, 11, and swap it with the card in the first place, 64. Now 11 is where it belongs, and it never has to move again.
The other four cards, 25, 12, 22 and 64, are still mixed up. So the same thing happens again, one place further right: the lowest of those four is 12, and it swaps with 25, which sits in the second place. Each round fixes one more place at the left.
The picture shows every round on the example. In each row, the teal boxes, marked sorted part in the key, are the places already fixed, and the rest of the row is the unsorted part. The blue box, front of the unsorted part, is the place this round fills. The orange box, smallest in the unsorted part, is the value that goes there.
In the row labelled pass 1, the whole array is unsorted, and 11 swaps with 64. In pass 2, 11 is in the sorted part, and 12 swaps with 25. Pass 3 swaps 25 and 22. In pass 4, the smallest of 25 and 64 is 25, which already sits at the front, so nothing moves.
Why stop after four rounds when there are five cards? After pass 4, the one value left in the unsorted part, 64, is larger than everything in the sorted part, so it is already in the last place. The row labelled sorted shows the result.
So each round selects the smallest remaining value and puts it in the next place, which is where the name selection sort comes from. That raises the real question: how much looking does it take to find each smallest value?
Solution Approach
Writing selection sort as code means answering four questions: how a pass finds the smallest value, how that value reaches the front, how many passes there are, and what happens to equal values.
Finding the smallest value in a pass
How does a pass know which value is smallest? It has to look at every value in the unsorted part, because the smallest could be anywhere, even last, as 11 is in pass 1. It keeps the position of the smallest value seen so far and compares each next value with it.
On the example, pass 1 compares 4 values against the smallest so far, pass 2 compares 3, pass 3 compares 2 and pass 4 compares 1. That makes 10 comparisons, and the count stays the same however the values are ordered, because no pass can stop before it has seen the whole unsorted part.
Moving the smallest value to the front
Once a pass knows where the smallest value is, how does it get to the front? One swap does it: the smallest value goes to the front of the unsorted part, and the value that was there takes its old place. In pass 1, 64 simply moves to where 11 was.
A pass could also swap every time it meets a value smaller than the front one, but each of those swaps is an extra write into the array. Remembering only the position and swapping once at the end keeps it to at most one swap per pass. When the smallest value is already at the front, as 25 is in pass 4, the swap is skipped.
Using so few swaps is the main strength of selection sort. Few swaps matter where writing a value costs far more than reading one, for example on flash memory, which wears out a little with every write.
How many passes
An array of n values needs n - 1 passes. Each pass fixes one place, and when n - 1 places are fixed, the last value is the largest, so it is already at the end. An array with one value or none needs no pass at all.
Equal values and stability
What happens when two values are equal? Sorted output does not show it for plain numbers, but it does when each value belongs to something, such as cards marked 5a, 5b and 2c, sorted by their number. A sort that always keeps equal items in their original order, 5a before 5b, is called stable.
Selection sort is not. Pass 1 finds 2c as the smallest and swaps it with the front card, 5a, so 5a jumps from the first place to the last, past 5b. Pass 2 sees 5b and 5a as equal and leaves them alone, so the cards end up as 2c, 5b, 5a.
Java Solution
The method sort
- First, store the length of the array in
and reset two counters,n andcomparisons . They only count the work, so thatswaps can print it.main - Run the passes with a loop over
from 0 toi . Heren - 2 is the front of the unsorted part, soi is pass 1.i = 0 - Inside, set
, the position of the smallest value seen so far, tominIdx . A second loop movesi over the positions afterj , and wheneveri ,arr[j] < arr[minIdx] becomesminIdx . Each comparison adds one toj .comparisons - After the second loop, if
is notminIdx , swapi andarr[i] through a temporary variable,arr[minIdx] , and add one totmp .swaps - When the outer loop ends, the array is sorted. There is no return value, since the sorted values now sit in
itself.arr
A second method, sortCardsrun
The mainint
import java.util.Arrays;
public class SelectionSort {
static int comparisons;
static int swaps;
public static void sort(int[] arr) {
comparisons = 0;
swaps = 0;
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIdx = i; // smallest value seen so far in arr[i..n-1]
for (int j = i + 1; j < n; j++) {
comparisons++;
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
if (minIdx != i) { // move it to the front of the unsorted part
int tmp = arr[i];
arr[i] = arr[minIdx];
arr[minIdx] = tmp;
swaps++;
}
}
}
// The same passes, comparing cards such as "5a" only by their number.
public static void sortCards(String[] cards) {
for (int i = 0; i < cards.length - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < cards.length; j++) {
if (cards[j].charAt(0) < cards[minIdx].charAt(0)) {
minIdx = j;
}
}
if (minIdx != i) {
String tmp = cards[i];
cards[i] = cards[minIdx];
cards[minIdx] = tmp;
}
}
}
static void run(int[] arr) {
String before = Arrays.toString(arr);
sort(arr);
System.out.println(before + " -> " + Arrays.toString(arr)
+ " comparisons=" + comparisons + ", swaps=" + swaps);
}
public static void main(String[] args) {
run(new int[] {64, 25, 12, 22, 11});
run(new int[] {11, 12, 22, 25, 64});
run(new int[] {64, 25, 22, 12, 11});
run(new int[] {12, 22, 25, 64, 11});
run(new int[] {3, 1, 3, 1});
run(new int[] {Integer.MAX_VALUE, -5, 0, Integer.MIN_VALUE});
run(new int[] {7});
run(new int[] {});
String[] cards = {"5a", "5b", "2c"};
sortCards(cards);
System.out.println(Arrays.toString(cards));
}
}
Running it prints:
[64, 25, 12, 22, 11] -> [11, 12, 22, 25, 64] comparisons=10, swaps=3
[11, 12, 22, 25, 64] -> [11, 12, 22, 25, 64] comparisons=10, swaps=0
[64, 25, 22, 12, 11] -> [11, 12, 22, 25, 64] comparisons=10, swaps=2
[12, 22, 25, 64, 11] -> [11, 12, 22, 25, 64] comparisons=10, swaps=4
[3, 1, 3, 1] -> [1, 1, 3, 3] comparisons=6, swaps=2
[2147483647, -5, 0, -2147483648] -> [-2147483648, -5, 0, 2147483647] comparisons=6, swaps=1
[7] -> [7] comparisons=0, swaps=0
[] -> [] comparisons=0, swaps=0
[2c, 5b, 5a]
Look at the first line: the example comes out as [11, 12, 22, 25, 64]
The next three lines hold the same five values in other orders, and each one still takes exactly 10 comparisons. Only the swaps change. The sorted input [11, 12, 22, 25, 64][64, 25, 22, 12, 11]
The input [12, 22, 25, 64, 11]
The line with 2147483647 and -2147483648, the largest and smallest intint[7][]n
The last line is the stability check: [2c, 5b, 5a]
Complexity
The number of comparisons depends only on the length of the array, and the order of the values changes only the number of swaps.
- Best case: O(n²), on an already sorted array such as
, because each pass must still scan its whole unsorted part to be sure the front value is the smallest, even though no swap follows.[11, 12, 22, 25, 64] - Average case: O(n²), on values in mixed order such as the example, because the passes compare n - 1, then n - 2, and so on down to 1 pair, which is n(n - 1)/2 comparisons, 10 for five values.
- Worst case: O(n²), with the most swaps on an input such as
, because the comparisons are the same n(n - 1)/2 and the swaps grow only to n - 1, one per pass.[12, 22, 25, 64, 11] - Space: O(1), because the sort works in place and keeps only
,i ,j andminIdx , whatever the size of the array.tmp