Skip to content

Commit 9f115d3

Browse files
committed
fix(sorts): accept lt-only items in recursive insertion sort
1 parent b3233c9 commit 9f115d3

2 files changed

Lines changed: 19 additions & 8 deletions

File tree

‎sorts/recursive_insertion_sort.py‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,14 @@
55
from __future__ import annotations
66

77
from collections.abc import MutableSequence
8-
from typing import Any, Protocol, TypeVar
8+
from typing import Protocol
99

1010

1111
class Comparable(Protocol):
12-
def __lt__(self, other: Any, /) -> bool: ...
12+
def __lt__(self, other: object, /) -> bool: ...
1313

1414

15-
T = TypeVar("T", bound=Comparable)
16-
17-
18-
def rec_insertion_sort[T](collection: MutableSequence[T], n: int) -> None:
15+
def rec_insertion_sort[T: Comparable](collection: MutableSequence[T], n: int) -> None:
1916
"""
2017
Given a collection of comparable elements and its length, sorts the
2118
collection in place in ascending order.
@@ -51,7 +48,7 @@ def rec_insertion_sort[T](collection: MutableSequence[T], n: int) -> None:
5148
rec_insertion_sort(collection, n - 1)
5249

5350

54-
def insert_next[T](collection: MutableSequence[T], index: int) -> None:
51+
def insert_next[T: Comparable](collection: MutableSequence[T], index: int) -> None:
5552
"""
5653
Inserts the '(index-1)th' element into place
5754
@@ -71,7 +68,7 @@ def insert_next[T](collection: MutableSequence[T], index: int) -> None:
7168
[]
7269
"""
7370
# Checks order between adjacent elements
74-
if index >= len(collection) or collection[index - 1] <= collection[index]:
71+
if index >= len(collection) or not collection[index] < collection[index - 1]:
7572
return
7673

7774
# Swaps adjacent elements since they are not in ascending order

‎tests/test_sorts.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,20 @@ def test_rec_insertion_sort_rejects_non_comparable_items() -> None:
186186
rec_insertion_sort([1, "a"], 2)
187187

188188

189+
def test_rec_insertion_sort_lt_only_items() -> None:
190+
class LessOnly:
191+
def __init__(self, value: int) -> None:
192+
self.value = value
193+
194+
def __lt__(self, other: object) -> bool:
195+
assert isinstance(other, LessOnly)
196+
return self.value < other.value
197+
198+
collection = [LessOnly(3), LessOnly(1), LessOnly(2)]
199+
rec_insertion_sort(collection, len(collection))
200+
assert [item.value for item in collection] == [1, 2, 3]
201+
202+
189203
def test_bogo_sort_comparable_items() -> None:
190204
assert bogo_sort(["c", "a", "b"]) == ["a", "b", "c"]
191205
assert bogo_sort([2.5, -1.0, 0.0]) == [-1.0, 0.0, 2.5]

0 commit comments

Comments
 (0)