AlgoVerse

Selection sort

In each round, find the smallest item of the unsorted part and move it to the front of that part.

The array has two parts: the sorted part at the front and the unsorted part after it. In each round, the smallest item of the unsorted part is found and swapped with the first item of that part. After round i, position i holds its final item.

Read the full explanation ↓
Input:
n=5PDF export

Five mixed numbers; four rounds, each putting one item in its final place.

  1. def selection_sort(a):
  2. n = len(a)
  3. for i in range(n - 1):
  4. smallest = i
  5. for j in range(i + 1, n):
  6. if a[j] < a[smallest]:
  7. smallest = j
  8. a[i], a[smallest] = a[smallest], a[i]
  9. return a

Invariant: At the start of each round, a[0..i−1] holds the i smallest items of the array, in order.

Start

640251122223114

Local variables

Orange = changed in this step

a list

6425122211

Call stack

  1. selection_sort()line 1
Step 1 of 45
Black = start · Orange = key stepcompare: 0/10 · swap: 0/4 · start: 0/4 · new_min: 0/5

    How the work grows with input size

    Average of 12 random graphs per n (fixed seeds). Hollow marker = the input on screen.

    • comparisons
    • swaps
    • current input (n=5)
    05010015046810121416n = number of itemscomparisonsswaps
    Show as a table
    ncomparisonsswaps
    463
    6155
    8287
    10459
    126611
    149113
    1612015
    Explanation

    The idea

    The array has two parts: the sorted part at the front and the unsorted part after it. In each round, the smallest item of the unsorted part is found and swapped with the first item of that part. After round i, position i holds its final item.

    Cost

    • The number of comparisons is always n(n − 1)/2, whatever the input: O(n²).
    • There are at most n − 1 swaps; when writing to memory is expensive, that is a real advantage.
    • Extra memory O(1).

    Stability

    Swapping the smallest item with a[i] can move an item past an equal one, so selection sort is not stable.

    What to watch in the trace

    • The smallest arrow shows the smallest item so far, and j walks through the rest.
    • Compare the number of compare steps on "already sorted" and "sorted backwards": it is the same.