Skip to content

Instantly share code, notes, and snippets.

@clohfink
Created August 13, 2026 14:52
Show Gist options
  • Select an option

  • Save clohfink/3aec326f31ccb129449f8512d82e836b to your computer and use it in GitHub Desktop.

Select an option

Save clohfink/3aec326f31ccb129449f8512d82e836b to your computer and use it in GitHub Desktop.
groundhog_sort.py
from itertools import permutations
from typing import Iterable, TypeVar
T = TypeVar("T")
def groundhog_sort(values: Iterable[T]) -> list[T]:
"""
Sort by regenerating every permutation from scratch
for each position in the output.
"""
items = tuple(values)
result: list[T] = []
for position in range(len(items)):
smallest: T | None = None
found_candidate = False
# Groundhog Day: generate every permutation all over again.
for permutation in permutations(items):
prefix_matches = True
for prefix_index in range(position):
if permutation[prefix_index] != result[prefix_index]:
prefix_matches = False
break
if not prefix_matches:
continue
candidate = permutation[position]
if not found_candidate or candidate < smallest:
smallest = candidate
found_candidate = True
if not found_candidate:
raise RuntimeError("No permutation matched the selected prefix")
result.append(smallest)
return result
numbers = [4, 2, 5, 1, 3]
print("Input: ", numbers)
print("Sorted:", groundhog_sort(numbers))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment