Skip to content
Open
Show file tree
Hide file tree
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
13 changes: 5 additions & 8 deletions sorts/recursive_insertion_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,14 @@
from __future__ import annotations

from collections.abc import MutableSequence
from typing import Any, Protocol, TypeVar
from typing import Protocol


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


T = TypeVar("T", bound=Comparable)


def rec_insertion_sort[T](collection: MutableSequence[T], n: int) -> None:
def rec_insertion_sort[T: Comparable](collection: MutableSequence[T], n: int) -> None:
"""
Given a collection of comparable elements and its length, sorts the
collection in place in ascending order.
Expand Down Expand Up @@ -51,7 +48,7 @@ def rec_insertion_sort[T](collection: MutableSequence[T], n: int) -> None:
rec_insertion_sort(collection, n - 1)


def insert_next[T](collection: MutableSequence[T], index: int) -> None:
def insert_next[T: Comparable](collection: MutableSequence[T], index: int) -> None:
"""
Inserts the '(index-1)th' element into place

Expand All @@ -71,7 +68,7 @@ def insert_next[T](collection: MutableSequence[T], index: int) -> None:
[]
"""
# Checks order between adjacent elements
if index >= len(collection) or collection[index - 1] <= collection[index]:
if index >= len(collection) or not collection[index] < collection[index - 1]:
return

# Swaps adjacent elements since they are not in ascending order
Expand Down
14 changes: 14 additions & 0 deletions tests/test_sorts.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,20 @@ def test_rec_insertion_sort_rejects_non_comparable_items() -> None:
rec_insertion_sort([1, "a"], 2)


def test_rec_insertion_sort_lt_only_items() -> None:
class LessOnly:
def __init__(self, value: int) -> None:
self.value = value

def __lt__(self, other: object) -> bool:
assert isinstance(other, LessOnly)
return self.value < other.value

collection = [LessOnly(3), LessOnly(1), LessOnly(2)]
rec_insertion_sort(collection, len(collection))
assert [item.value for item in collection] == [1, 2, 3]


def test_bogo_sort_comparable_items() -> None:
assert bogo_sort(["c", "a", "b"]) == ["a", "b", "c"]
assert bogo_sort([2.5, -1.0, 0.0]) == [-1.0, 0.0, 2.5]
Expand Down
Loading