Skip to content

Selection Sort ​

Selection sort is a sort that goes through the positions from the front, picks (selects) the smallest value that belongs in each position and puts it there.

At a Glance ​

  • It is similar to bubble sort, but the position to fill is already fixed, and the algorithm selects which element goes there.
  • Selection sort and insertion sort are often confused. An easy way to remember it: selection sort picks the position first, then finds the value that belongs there.
  • Analogy: at a race awards ceremony, you find the person for the 1st-place spot among everyone and place them, then find the person for the 2nd-place spot among the rest, and so on.
  • In terms of classification, it is a comparison sort, an unstable sort (equal values may change order) and an in-place sort (only swaps positions within the array).

How It Works ​

This is for sorting in ascending order.

  1. Find the minimum value in the given array.
  2. Swap it with the value at the front. (One round of this is called a pass.)
  3. Repeat the same method on the rest of the array, excluding the first position.

Let's follow along with the example array [4, 2, 5, 1].

PassPosition to fillMinimum foundArray stateExplanation
Start--[4, 2, 5, 1]Initial state
Pass 1Position 01 (position 3)[1, 2, 5, 4]Swap 4 and 1
Pass 2Position 12 (position 1)[1, 2, 5, 4]Already in place, so it swaps with itself
Pass 3Position 24 (position 3)[1, 2, 4, 5]Swap 5 and 4. Sorting complete

The last position has only one value left, so it does not need a separate pass.

In Pictures ​

Selection sort in action

Image source: GimunLee/tech-refrigerator (Apache-2.0)

Python Code ​

python
def selection_sort(arr):
    """Selection sort that picks the minimum of the remaining values for each position (ascending)"""
    n = len(arr)
    for i in range(n - 1):                 # 1.
        index_min = i
        for j in range(i + 1, n):          # 2.
            if arr[j] < arr[index_min]:    # 3.
                index_min = j
        arr[i], arr[index_min] = arr[index_min], arr[i]   # 4.
    return arr


print(selection_sort([4, 2, 5, 1]))
# Output: [1, 2, 4, 5]
  1. First, select the position (index) i to fill. Assume for now that the value at that position is the minimum and set index_min = i.
  2. Go from element i + 1 to the end, comparing each value with the minimum so far.
  3. Since the order is ascending, if the current value is smaller than the minimum so far, change index_min to that position.
  4. When loop 2 finishes, index_min holds the position of the value that belongs in the position chosen in step 1. So the two values are swapped.

Time and Space Complexity ​

With n data items, the number of comparisons is as follows.

  • Pass 1: compare with elements 1 to (n-1) → n-1 comparisons
  • Pass 2: compare with elements 2 to (n-1) → n-2 comparisons
  • …
  • Total: (n-1) + (n-2) + ... + 2 + 1 = n(n-1)/2

Assuming each comparison takes constant time, sorting n items takes O(n²) time. Even if the array is already sorted, it has to look all the way to the end to confirm "the minimum of what remains," so the best, average and worst cases are all the same. (For Big-O notation, see the time complexity article.)

CaseTime complexity
BestO(n²)
AverageO(n²)
WorstO(n²)
SpaceExtra memory O(1) (O(n) including input)
  • Space: it only swaps within the given array, so the extra memory beyond the input array is O(1).
  • There is at most 1 swap per pass, so at most n-1 swaps in total, i.e. O(n). There are many comparisons but few swaps.

Pros and Cons ​

Pros ​

  • Like bubble sort, the algorithm is simple.
  • It makes many comparisons but fewer actual swaps than bubble sort, so it is relatively efficient for data that would need many swaps.
  • Like bubble sort, it swaps within the array, so it needs no other memory space. → In-place sorting

Cons ​

  • Its time complexity is O(n²), which is inefficient.
  • It is an unstable sort. Because it swaps two values that may be far apart in one step, equal values can end up in reversed order.

Let's look at an unstable example. To tell the two equal values 5 apart, we label them 5a and 5b.

PassArray stateExplanation
Start[5a, 5b, 2]5a comes before 5b
Pass 1[2, 5b, 5a]Swap the minimum 2 with 5a at the front. 5a is pushed to the end
Pass 2[2, 5b, 5a]5b and 5a are equal, so no swap

The sort is finished, but the order of 5a and 5b is the reverse of what it was at the start.

Wrapping Up ​

We looked at selection sort, which is similar to bubble sort but a little faster because it swaps less. It shows up fairly often in technical interviews and exams ("What does the array look like after the n-th pass?"), so it is good to know.

Summary ​

ConceptPlain-language summary
Selection sortStarting from the 1st-place spot, pick the smallest of the remaining values and place it
PassOne round that fixes one position
Number of swapsAt most one per round, so few
Unstable sortBecause it swaps with far-away values, equal values may end up in reversed order

Source: GimunLee/tech-refrigerator (Apache-2.0), code rewritten in Python

Reference: jinhyy - Sorting Algorithms