Selection Sort, step by step.

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

What is selection sort?

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.

Why is it called selection sort?

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.

Selection sort algorithm: passes, the minimum and one swap

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.

Selection sort example: the first pass

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 first pass

All steps as text
  1. Sort the array using the Selection Sort algorithm.
  2. Mark the first element as the initial minimum.
  3. Scan the rest of the array for an element smaller than the current minimum.
  4. When you find a smaller element, mark it as the new minimum.
  5. Scan the rest of the array for an element smaller than the current minimum.
  6. When you find a smaller element, mark it as the new minimum.
  7. Scan the rest of the array for an element smaller than the current minimum.
  8. When you find a smaller element, mark it as the new minimum.
  9. Scan the rest of the array for an element smaller than the current minimum.
  10. After scanning, identify the true minimum element for this pass.
  11. Since the sorted section is initially empty, swap the identified minimum element with the first element in the array.
  12. With one element sorted, repeat the process until the array is fully sorted.
  13. Pass 1 made six comparisons and one swap. 0, the smallest element, is now at the front.
Selection Sort — The first pass. Last step: Pass 1 made six comparisons and one swap. 0, the smallest element, is now at the front.

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.

Selection sort example: the remaining passes

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.

The remaining passes

All steps as text
  1. The first pass has moved 0, the smallest element, to the front. Each new pass scans one element fewer.
  2. Consider the first element in the unsorted part as the initial minimum.
  3. Scan the rest of the array for an element smaller than the current minimum.
  4. When you find a smaller element, mark it as the new minimum.
  5. Scan the rest of the array for an element smaller than the current minimum.
  6. After scanning, identify the true minimum element for this pass.
  7. Swap the minimum element with the leftmost element of the unsorted part.
  8. Extend the sorted part and continue the process until the array is fully sorted.
  9. Consider the first element in the unsorted part as the initial minimum.
  10. Scan the rest of the array for an element smaller than the current minimum.
  11. After scanning, identify the true minimum element for this pass.
  12. No swap needed as the minimum element is already the leftmost in the unsorted part.
  13. Consider the first element in the unsorted part as the initial minimum.
  14. Scan the rest of the array for an element smaller than the current minimum.
  15. When you find a smaller element, mark it as the new minimum.
  16. After scanning, identify the true minimum element for this pass.
  17. Swap the minimum element with the leftmost element of the unsorted part.
  18. Extend the sorted part and continue the process until the array is fully sorted.
  19. Consider the first element in the unsorted part as the initial minimum.
  20. Scan the rest of the array for an element smaller than the current minimum.
  21. When you find a smaller element, mark it as the new minimum.
  22. After scanning, identify the true minimum element for this pass.
  23. Swap the minimum element with the leftmost element of the unsorted part.
  24. Extend the sorted part and continue the process until the array is fully sorted.
  25. Consider the first element in the unsorted part as the initial minimum.
  26. Scan the rest of the array for an element smaller than the current minimum.
  27. When you find a smaller element, mark it as the new minimum.
  28. After scanning, identify the true minimum element for this pass.
  29. Swap the minimum element with the leftmost element of the unsorted part.
  30. The entire array is sorted.
  31. Passes 2 to 6 made 15 comparisons and four swaps. The whole sort took 21 comparisons and five swaps.
Selection Sort — The remaining passes. Last step: The array is sorted: 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.

Seven rows of seven cells, labeled Start and Pass 1 to Pass 6. Start is the unsorted array 5, 2, 1, 4, 0, 6, 3; after pass 1 it is 0, 2, 1, 4, 5, 6, 3; after pass 2, 0, 1, 2, 4, 5, 6, 3; after pass 3 it is unchanged; after pass 4, 0, 1, 2, 3, 5, 6, 4; after pass 5, 0, 1, 2, 3, 4, 6, 5; after pass 6, 0, 1, 2, 3, 4, 5, 6. Under each pass row a bracket covers the sorted cells at the left end, labeled Sorted in the first: one cell after pass 1, two after pass 2, and so on, and all seven after pass 6.
Each pass swaps the smallest unsorted value to the front of the unsorted part and widens the Sorted bracket from the left; pass 3 finds 2 already in place and swaps nothing.

Selection sort is not adaptive

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.

An already sorted array

All steps as text
  1. Sort the array using the Selection Sort algorithm.
  2. Mark the first element as the initial minimum.
  3. Scan the rest of the array for an element smaller than the current minimum.
  4. After scanning, identify the true minimum element for this pass.
  5. With one element sorted, repeat the process until the array is fully sorted.
  6. Pass 1 made six comparisons and no swap. Selection sort is not adaptive: passes 2 to 6 would still make 15 more comparisons, 21 in all for seven values.
Selection Sort — An already sorted array. Last step: Pass 1 marked 0 as sorted, and the array 0, 1, 2, 3, 4, 5, 6 is unchanged.

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.

What happens in the first pass of selection sort?

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.

Is selection sort adaptive?

No. An already sorted array costs the same n(n − 1)/2 comparisons as any other order, as the third player shows.

Is selection sort stable?

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.

Selection sort time complexity: comparisons and swaps

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.

CaseComparisonsSwapsTimeExtra space
Best: already sortedn(n − 1)/20O(n2)O(1)
Average: random ordern(n − 1)/2At most n − 1O(n2)O(1)
Worst: a rotation by one place, such as 1, 2, 3, 4, 5, 6, 0n(n − 1)/2n − 1O(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.

Why selection sort is not stable

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.

Two rows of three cells, labeled Start and Pass 1. Start holds a 2 marked a, a 2 marked b, and 1. After pass 1 the row is 1, the 2 marked b, the 2 marked a, with a Sorted bracket under the first cell: 1 and the first 2 have swapped, and the two equal 2s have changed order.
Pass 1 swaps the minimum, 1, with the first 2, which jumps over the second 2: the equal values end in reversed order, so selection sort is not stable.

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.

Selection sort vs bubble sort vs insertion sort

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: selection sort with a heap

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.

Selection sort in Python, Java and C++

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++.

When selection sort is used

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:

  • Memory where writes cost more than reads, such as flash, and arrays of large records. It makes at most n − 1 swaps, though cycle sort makes even fewer writes.
  • Small arrays and teaching.
  • The k smallest values in order: k passes take 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.

Three animations here.
The whole topic 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.

Your own 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.

Forward and back

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.

Theory and complexity

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.

Python, Java and C++

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.

Quiz

Eight questions with an explanation for every answer, from what the first k positions hold to why selection sort cannot stop early.

Five more sorts

Bubble sort, insertion sort, merge sort, heap sort and quick sort each have a topic of their own.

Sort an array
one minimum at a time.

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