Algorithms

Insert each element into the sorted part on its left — O(n²), fast on nearly sorted data.

Version 1.1.0 Versions: 1.2.0 1.1.0 1.0.0

This is an older version. The current version is 1.2.0.

Implementations

Sign in to open in IDE Sign in with your Zerethon account to create your own copy of this sample.

Files

README.md
# Insertion Sort

Zerethon Official Sample `insertion-sort`, version 1.1.0, Python 3.12.

- `insertion_sort.py` — the algorithm, as shown in Zerethon Tools
- `main.py` — entry file: a short demonstration
- `test_insertion_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/insertion-sort-visualizer
insertion_sort.py
"""Insertion Sort (Zerethon Official Sample: insertion-sort 1.1.0)."""


def insertion_sort(a):
    for i in range(1, len(a)):
        key = a[i]
        j = i - 1
        while j >= 0 and a[j] > key:
            a[j + 1] = a[j]
            j -= 1
        a[j + 1] = key
    return a
main.py entry
from insertion_sort import insertion_sort

numbers = [38, 27, 43, 3, 9, 82, 10, 27]
print("Before:", numbers)
result = insertion_sort(list(numbers))
print("After: ", result)
print("Same as sorted():", result == sorted(numbers))
test_insertion_sort.py
# Checks for insertion_sort. To run them, set this file as the entry file
# (the ▶ button next to it in Files) and press Run.
from insertion_sort import insertion_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 = insertion_sort(list(case))
    assert got == sorted(case), f"insertion_sort({case[:6]}...) = {got[:6]}..."

print(f"All {len(cases)} checks passed.")

Source: Zerethon Official Sample. Algorithm as shown in the Zerethon Tools Insertion Sort Visualizer.