Skip to content
Merged
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
2 changes: 1 addition & 1 deletion sorts/adaptive_merge_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def merge(array: list, aux: list, low: int, mid: int, high: int) -> None:
for k in range(low, high + 1):
array[k] = aux[k]

print(f"After merge: {array[low:high + 1]}")
print(f"After merge: {array[low : high + 1]}")


# Example usage
Expand Down
15 changes: 14 additions & 1 deletion sorts/binary_insertion_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,17 @@
python binary_insertion_sort.py
"""

from typing import Protocol, TypeVar

def binary_insertion_sort(collection: list) -> list:

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


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


def binary_insertion_sort[T: Comparable](collection: list[T]) -> list[T]:
"""
Sorts a list using the binary insertion sort algorithm.

Expand All @@ -36,6 +45,10 @@ def binary_insertion_sort(collection: list) -> list:
>>> collection = random.choices(string.ascii_letters + string.digits, k=100)
>>> binary_insertion_sort(collection) == sorted(collection)
True
>>> binary_insertion_sort([1, "a"])
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""

n = len(collection)
Expand Down
5 changes: 5 additions & 0 deletions tests/test_sorts.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,8 @@ def test_heap_sort():
def test_sort_matches_builtin(sort, case):
"""Each sort must reproduce the ordering of the built-in ``sorted``."""
assert list(sort(list(case))) == sorted(case)


def test_binary_insertion_sort_rejects_non_comparable_items():
with pytest.raises(TypeError):
binary_insertion_sort([1, "a"])
Loading