Selection sort is a simple sorting algorithm that repeatedly finds the minimum of the unsorted part and swaps it to the front of that part, so the sorted part grows from the left. It takes O(n²) time in every case, makes at most n − 1 swaps, needs O(1) extra space and is not stable. This page explains how it works, with step-by-step animations of the first pass, the remaining passes and an already sorted array from the VisiGrab app.
// how selection sort works
Selection sort is a simple sorting algorithm that splits an array into a sorted part on the left and an unsorted part on the right. Each pass finds the minimum of the unsorted part and swaps it to the front of that part, so the sorted part grows by one element. Selection sort takes O(n2) time in every case and O(1) extra space, and it is not stable.
Each pass selects the smallest remaining value and puts it in its final place. Some textbooks select the largest value instead and grow the sorted part from the right: the same algorithm, mirrored.
Positions count from 0, as in the app. Pass k takes the value at position k − 1 as the initial minimum and scans the n − k values to its right. One swap after the scan moves the minimum to position k − 1. n − 1 passes are enough, because the last pass settles two values.
In pseudocode:
for i from 0 to n - 2
minIndex = i
for j from i + 1 to n - 1
if a[j] < a[minIndex]
minIndex = j
swap a[i] and a[minIndex]
The outer loop runs i from 0 to n − 2 and sets minIndex = i. The inner loop runs j from i + 1 and sets minIndex = j when a[j] < a[minIndex]. Then a[i] and a[minIndex] swap.
Common mistakes are swapping inside the inner loop, keeping the minimum's value instead of its index, and starting the inner loop at 0. Swapping inside the inner loop still sorts, but makes up to n(n − 1)/2 swaps.
The player runs the first pass on the app's default array, 5, 2, 1, 4, 0, 6, 3. The min label moves from 5 to 2, 1 and finally 0, and after six comparisons 0 swaps with 5: 0, 2, 1, 4, 5, 6, 3.
The minimum changed three times, but only one swap followed. It carried 5 four places right, past 2, 1 and 4. Such long jumps make selection sort unstable.
Each new pass starts one position further right and scans one element fewer. In pass 3 the minimum, 2, is already in place, so the app says no swap is needed. Pass 6 settles the last two values at once: 0, 1, 2, 3, 4, 5, 6.
After k passes, the first k positions hold the k smallest values in their final order. The figure shows the array after every pass.
An adaptive sort does less work on input that is already in order. Selection sort cannot: it knows the minimum only after looking at every candidate. On the sorted array 0, 1, 2, 3, 4, 5, 6, pass 1 marks 0 as the initial minimum and compares it with the six values to its right. Nothing is smaller, so there is no swap, and the bracket appears under position 0.
Passes 2 to 6 would still make 5, 4, 3, 2 and 1 comparisons. With the six of pass 1, that is 21 in all, as on the default array. Only the swaps and the new minima depend on the input. Bubble sort with an early exit stops here after one pass of six comparisons.
Pass 1 takes the first value as the minimum and compares each of the other n − 1 values with the current minimum, replacing it whenever a value is smaller. At most one swap then moves the smallest value of the whole array to position 0, its final place. The first player shows that swap at step 13.
No. An already sorted array costs the same n(n − 1)/2 comparisons as any other order, as the third player shows.
No. A swap can carry a value past an equal one, so equal values can end up in reversed order; the example below shows how.
Pass k makes n − k comparisons, so every input costs (n − 1) + (n − 2) + … + 1 = n(n − 1)/2: 21 for seven values, about 50 million for 10,000. The best, average and worst cases are therefore all O(n2). Each pass makes at most one swap, so the sort makes at most n − 1. The extra memory is an index and one temporary value, so selection sort is in-place.
| Case | Comparisons | Swaps | Time | Extra space |
|---|---|---|---|---|
| Best: already sorted | n(n − 1)/2 | 0 | O(n2) | O(1) |
| Average: random order | n(n − 1)/2 | At most n − 1 | O(n2) | O(1) |
| Worst: a rotation by one place, such as 1, 2, 3, 4, 5, 6, 0 | n(n − 1)/2 | n − 1 | O(n2) | O(1) |
Reverse-sorted input is not the worst case for swaps: 6, 5, 4, 3, 2, 1, 0 needs three, because each swap places two values. With distinct values, selection sort makes the fewest swaps any sort can: n minus the number of cycles, groups of values that only trade places among themselves. The default array has two: 1 and 2 trade places, and 0, 3, 4, 5 and 6 rotate, so it takes 7 − 2 = 5.
A stable sort keeps equal values in their original order. Selection sort does not. In 2a, 2b, 1, pass 1 keeps 2a as the minimum, since 2b is not smaller, and then finds 1. 1 and 2a swap: 1, 2b, 2a. Pass 2 changes nothing, so the two 2s stay in reversed order.
Taking an equal value as the new minimum makes it worse: the scan then picks the last of several equal minima, which jumps over the others. The value displaced from the front still jumps over its equals. A stable version shifts the values in between one place right instead of swapping, at the cost of O(n2) writes.
On the default array, selection sort makes 21 comparisons and five swaps. Bubble sort with its early exit makes 20 comparisons and 11 swaps, one per inversion. Each selection swap removes at least one inversion, so selection sort never swaps more than bubble sort. On large random arrays insertion sort makes about half as many comparisons; on the default array it makes 14. It is also stable and adaptive. But it makes one shift per inversion, about n2/4 on average, where selection sort makes at most n − 1 swaps. So selection sort wins only where writes are expensive.
Heap sort keeps the unsorted part in a binary heap. Each selection takes the heap's root, as extract-min does in a min-heap. That costs O(log n) instead of an O(n) scan, so the whole sort takes O(n log n). It is in-place and unstable too. The usual version, as in the app's Heap Sort topic, builds a max-heap and moves the root to the end, so its sorted part grows from the right.
The app shows the code in all three, linked to the full source on GitHub. The listings make the same comparisons, taking only a strictly smaller value as the new minimum, and sort the caller's array in place. Java swaps through a temporary variable, Python with a tuple assignment and C++ with std::swap. All three swap after every scan, even a value with itself when the minimum is already in place. A check that the minimum's index is not i avoids this harmless step, which the app's animation skips.
Note
In C++, std::min_element returns the first of equal minima, as the scan does, so each pass can be written as std::iter_swap(it, std::min_element(it, last)).
Note
In Python, the shortcut arr.index(min(arr[i:]), i) copies the unsorted part on every pass and scans it twice. min(range(i, n), key=lambda j: arr[j]) finds the minimum's index in one scan, without a copy.
The full source code is on GitHub, in Python, Java and C++.
Library sort functions do not use selection sort; for short runs they use insertion sort. LLVM's libc++ uses it only in std::nth_element, for ranges of four to seven values. Selection sort suits:
O(kn) time.Low memory alone is no reason to choose it: bubble sort and insertion sort also need O(1) extra space. For descending order, select the maximum instead. Double selection sort finds the minimum and the maximum in one pass and places both, at the two ends. Selection sort is neither recursive nor divide and conquer, though a recursive version can be written at the cost of O(n) stack.
// in the app
In VisiGrab selection sort runs on the default, a random or your own array of seven values, with a step for every comparison, new minimum and swap: 51 steps on the default array.
Random fills seven distinct values from 0 to 19. Custom opens a seven-cell dialog for values from 0 to 99, so a sorted array, a reversed one or one with equal values can be tried.
Step through every comparison, new minimum, swap and pass, each with its message, and step back through them. Restart replays the array, and the last array you used comes back next time.
One page: the sorted and unsorted parts, in-place, unstable and non-adaptive, often fewer swaps than bubble sort but many comparisons, and O(n²) in every case.
The selectionSort method in Java and the selection_sort function in Python and C++, each explained as moving the boundary between the sorted and unsorted parts one element right. Links lead to the full source on GitHub.
Eight questions with an explanation for every answer, from what the first k positions hold to why selection sort cannot stop early.
Bubble sort, insertion sort, merge sort, heap sort and quick sort each have a topic of their own.
// build your own
Download VisiGrab and step through every pass of selection sort, on the default array, on a sorted one or on an array of your own.
Selection sort is one of 30+ topics. See them all