Python Program for Selection Sort (With Pass-by-Pass Output)

A junior developer I mentor had to write a Python program for selection sort on a whiteboard, with no sorted() allowed. The answer is a loop that finds the smallest remaining value and swaps it forward, but he kept swapping inside the inner loop.

That bug still sorts, so it slips through. You want one swap per pass.

Quick answer: for each position, find the index of the smallest item from there on, then swap it into place:

for i in range(len(items) - 1):
    j = min(range(i, len(items)), key=items.__getitem__)
    items[i], items[j] = items[j], items[i]

In this tutorial, I’ll build a Python program for selection sort, trace it pass by pass, sort in descending order and by key, read numbers you type and time it against sorted().

How does selection sort work in Python?

The list has a sorted left part and an unsorted right part. Each pass swaps the minimum of the right part to its front. Every example uses the same six Q1 2026 invoice totals on Python 3.12.5.

def usd(xs):
    return ", ".join(f"${x:.2f}" for x in xs)

def selection_sort(items):
    n = len(items)
    for i in range(n - 1):
        smallest = i
        for j in range(i + 1, n):
            if items[j] < items[smallest]:
                smallest = j
        items[i], items[smallest] = items[smallest], items[i]
        print(f"Pass {i + 1}: {usd(items)}")
    return items

invoices = [349.99, 120.50, 89.00, 512.75, 120.50, 64.25]
selection_sort(invoices)

Output:

Pass 1: $64.25, $120.50, $89.00, $512.75, $120.50, $349.99
Pass 2: $64.25, $89.00, $120.50, $512.75, $120.50, $349.99
Pass 3: $64.25, $89.00, $120.50, $512.75, $120.50, $349.99
Pass 4: $64.25, $89.00, $120.50, $120.50, $512.75, $349.99
Pass 5: $64.25, $89.00, $120.50, $120.50, $349.99, $512.75
VS Code output of a Python selection sort printing the invoice list after each of the five passes
Each pass locks one invoice in place; five passes sort the list.

The outer loop runs n - 1 times; the last item’s already in place. The inner loop only tracks an index, and the swap is plain tuple unpacking, like when you swap two numbers in Python. Pass 3 swapped $120.50 with itself.

Selection sort in descending order

To put the biggest invoice first, track the largest value and flip the comparison:

if items[j] > items[largest]:   # was <
    largest = j

On the same invoices that printed $512.75 first and $64.25 last. If you’ve already sorted ascending, you can reverse the list in Python instead.

Is selection sort stable? Sorting records by a key

For rows of data, I gave the function a key argument, like sorted() has, and sorted four orders:

def selection_sort(items, key=lambda x: x):
    n = len(items)
    for i in range(n - 1):
        best = i
        for j in range(i + 1, n):
            if key(items[j]) < key(items[best]):
                best = j
        items[i], items[best] = items[best], items[i]
    return items

orders = [
    ("Olivia Carter", "TX", 120.50),
    ("Noah Bennett", "CA", 120.50),
    ("Ethan Brooks", "OH", 89.00),
    ("Mia Ramirez", "TX", 64.25),
]
by_total = lambda r: r[2]
results = {"selection_sort:": selection_sort(orders[:], by_total),
           "sorted():": sorted(orders, key=by_total)}
for label, rows in results.items():
    print(label)
    for name, state, total in rows:
        print(f"  {name:<14} {state}  ${total:.2f}")

Output:

selection_sort:
  Mia Ramirez    TX  $64.25
  Ethan Brooks   OH  $89.00
  Noah Bennett   CA  $120.50
  Olivia Carter  TX  $120.50
sorted():
  Mia Ramirez    TX  $64.25
  Ethan Brooks   OH  $89.00
  Olivia Carter  TX  $120.50
  Noah Bennett   CA  $120.50
VS Code output comparing a Python selection sort by key with sorted() on orders with equal totals
The two $120.50 orders switch places in the selection sort, while sorted() keeps Olivia Carter first.

Selection sort isn’t stable: the long swap moved Olivia Carter behind Noah Bennett. sorted() keeps ties in order, which you’ll need when you sort a list of tuples by two fields.

Selection sort on numbers the user enters

This version reads prices with input() and converts each one with float():

# usd() from the first example

# selection_sort() from the first example, minus the print

raw = input("Enter prices separated by spaces: ")
prices = [float(p) for p in raw.split()]
print("Sorted:", usd(selection_sort(prices)))

Output:

Enter prices separated by spaces: 19.99 5.49 42.00 7.25 12.80
Sorted: $5.49, $7.25, $12.80, $19.99, $42.00
Command Prompt running a Python selection sort program that reads five prices typed by the user
The five typed prices come back sorted from $5.49 to $42.00.

How fast is selection sort compared with sorted()?

It always makes n(n-1)/2 comparisons, so it’s O(n²) even on sorted input, with at most n – 1 swaps. Here’s 2,000 random prices:

import random
import timeit

# selection_sort() from the first example, minus the print

random.seed(2026)
data = [round(random.uniform(5, 900), 2) for _ in range(2000)]

t_sel = timeit.timeit(lambda: selection_sort(data[:]), number=5) / 5
t_py = timeit.timeit(lambda: sorted(data), number=5) / 5
print(f"selection_sort: {t_sel * 1000:.1f} ms")
print(f"sorted():       {t_py * 1000:.2f} ms")
print(f"sorted() was {t_sel / t_py:.0f}x faster")

Output:

selection_sort: 72.9 ms
sorted():       0.23 ms
sorted() was 321x faster
VS Code output timing a Python selection sort against sorted() on 2,000 random prices with timeit
Built-in sorted() finished hundreds of times faster than the hand-written selection sort.

sorted() runs Timsort in C. On nearly sorted data, insertion sort is the better simple sort.

Common selection sort mistakes and how to fix them

Swapping inside the inner loop. That’s a slower exchange sort. Move the swap after the scan.

Expecting a new list. It sorts in place, so pass items[:] if you’ll need the original.

To compare it with other hand-written sorts, start with these:

Frequently asked questions

What is the time complexity of selection sort?

O(n²) in every case, because it always scans the whole unsorted part. Extra space is O(1).

Is selection sort stable?

No. A swap can jump an item past an equal one. Use sorted() when tie order matters.

How many swaps does selection sort make?

At most n – 1, one per pass.

What’s the difference between selection sort and bubble sort?

Bubble sort swaps neighbors many times per pass; selection sort swaps once.

Can selection sort sort strings?

Yes, alphabetically, since Python compares strings with <. Mixing strings and numbers raises TypeError.

Where can I read about sorting in Python?

The official Sorting Techniques HOWTO covers keys and stability.