Selection sort

Each pass selects the smallest remaining value and swaps it into the next position on the left. The sorted prefix grows one cell at a time.

Algorithms Beginner Sorting ~7 min
The idea

Select the next minimum

Selection sort divides the array into a sorted prefix and an unsorted suffix. It scans the suffix for the minimum, then swaps that minimum into the boundary position.

Unlike bubble sort, it does at most one swap per pass — but it still examines every unsorted element.

TipCompare with bubble sort: same O(n²) comparisons, fewer swaps.
IdeaFind-min then swap
selection_sort.pyPython
for i in range(n - 1):
    min_i = i
    for j in range(i + 1, n):
        if arr[j] < arr[min_i]: min_i = j
    arr[i], arr[min_i] = arr[min_i], arr[i]

Start: [5, 2, 8, 1, 4]

Interactive

Run the simulation

Green bars are sorted. The mint bar is the current minimum candidate; blue is being compared.

Step 0 / 0
demo.pyPython
Bars + variablesdemo
Ready
Shortcuts: Space play/pause · → step · ← back · R reset
Remember

Selection sort essentials

Grow a sorted prefix by repeatedly placing the next minimum.

Prefix

Sorted region grows left→right

After pass i, indices 0…i are in final order.

1 swap

At most one swap per pass

You may scan many cells, but you only swap the min into place once.

O(n²)

Still quadratic

Finding the min each time means nested loops — simple, not fast.