Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions sorts/insertion_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,17 @@ def insertion_sort[T: Comparable](collection: MutableSequence[T]) -> MutableSequ
True
>>> values
[1, 2, 4, 7]

Equal-priority items retain their original relative order:
>>> from dataclasses import dataclass, field
>>> @dataclass(order=True)
... class Item:
... priority: int
... label: str = field(compare=False)
>>> items = [Item(2, "A"), Item(1, "X"), Item(2, "B"), Item(1, "Y")]
>>> [(item.priority, item.label) for item in insertion_sort(items)]

@cclauss cclauss Oct 3, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use @dataclass(order=True) so you can just insertion_sort(items) instead of adding an extra list comprehension.

Python/tests/test_sorts.py

Lines 134 to 137 in 84b73d0

@dataclass(order=True)
class Person:
name: str = "Bob"
age: int = 37

[(1, 'X'), (1, 'Y'), (2, 'A'), (2, 'B')]

>>> import random
>>> collection = random.sample(range(-50, 50), 100)
>>> insertion_sort(collection) == sorted(collection)
Expand Down
Loading