Selection Sort
See it animated in Zerethon Tools ↗Pick the smallest remaining element and swap it into place — O(n²), at most n−1 swaps.
Implementations
Sign in to open in IDE
Sign in with your Zerethon account to create your own copy of this sample.
Files
# Selection Sort
Zerethon Official Sample `selection-sort`, version 1.2.0, Python 3.12.
- `selection_sort.py` — the algorithm, as shown in Zerethon Tools
- `main.py` — entry file: a short demonstration
- `test_selection_sort.py` — checks; set it as the entry file to run them
This project is your own copy. Changing it never changes the official sample.
See the algorithm animated: https://tools.zerethon.com/selection-sort-visualizer
from selection_sort import selection_sort
numbers = [38, 27, 43, 3, 9, 82, 10, 27]
print("Before:", numbers)
result = selection_sort(list(numbers))
print("After: ", result)
print("Same as sorted():", result == sorted(numbers))
"""Selection Sort (Zerethon Official Sample: selection-sort 1.2.0)."""
def selection_sort(a):
n = len(a)
for i in range(n - 1):
m = i
for j in range(i + 1, n):
if a[j] < a[m]:
m = j
if m != i:
a[i], a[m] = a[m], a[i]
return a
# Checks for selection_sort. To run them, set this file as the entry file
# (the ▶ button next to it in Files) and press Run.
from selection_sort import selection_sort
def numbers(seed, count):
"""Deterministic pseudo-random integers in [-50, 49]."""
out = []
for _ in range(count):
seed = (seed * 1103515245 + 12345) % 2**31
out.append(seed % 100 - 50)
return out
cases = [[], [1], [2, 1], [1, 2, 3], [3, 2, 1], [5, 1, 5, 1, 5], [-3, 0, -1, 2]]
cases += [numbers(seed, size) for seed, size in ((1, 10), (2, 50), (3, 200))]
for case in cases:
got = selection_sort(list(case))
assert got == sorted(case), f"selection_sort({case[:6]}...) = {got[:6]}..."
print(f"All {len(cases)} checks passed.")
Source: Zerethon Official Sample. Algorithm as shown in the Zerethon Tools Selection Sort Visualizer.