Start free

Advanced · Sorting algorithms · 169 of 264

Selection sort, step by step

Selection sort: for each position from the left, find the smallest remaining number and swap it there. Print the list after each pass (one pass per position except the last).

Input: whole numbers on one line (at least 2). Output: the list after each pass.

Examples

Input
3 1 2
Output
1 3 2
1 2 3
Input
4 3 2 1
Output
1 3 2 4
1 2 3 4
1 2 3 4
Input
1 2
Output
1 2

One more test checks other inputs when you press Check.

Stuck? The idea behind sorting algorithms

Bubble sort swaps neighbours that are in the wrong order, pass after pass. Insertion sort takes each item in turn and slides it back into place among those before it. Merge sort splits the list, sorts each half and merges them.

These exercises ask for the steps, not just the result: write the algorithm yourself rather than calling sorted().

a = [5, 1, 4, 2]
for end in range(len(a) - 1, 0, -1):
    for i in range(end):
        if a[i] > a[i + 1]:
            a[i], a[i + 1] = a[i + 1], a[i]
print(a)

Watch for: Off-by-one: comparing a[i] with a[i + 1] means i must stop one before the end.

All the sorting algorithms exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More sorting algorithms exercises