Skip to content

Commit 16fd0d5

Browse files
modusensuscclauss
andauthored
sorts: make merge_insertion_sort generic over Comparable items (#15417)
Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent c4d6a2a commit 16fd0d5

2 files changed

Lines changed: 13 additions & 4 deletions

File tree

‎sorts/merge_insertion_sort.py‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,14 @@
1313

1414
from __future__ import annotations
1515

16+
from typing import Any, Protocol
1617

17-
def binary_search_insertion(sorted_list, item):
18+
19+
class Comparable(Protocol):
20+
def __lt__(self, other: Any, /) -> bool: ...
21+
22+
23+
def binary_search_insertion[T: Comparable](sorted_list: list[T], item: T) -> list[T]:
1824
"""
1925
>>> binary_search_insertion([1, 2, 7, 9, 10], 4)
2026
[1, 2, 4, 7, 9, 10]
@@ -35,7 +41,7 @@ def binary_search_insertion(sorted_list, item):
3541
return sorted_list
3642

3743

38-
def merge(left, right):
44+
def merge[T: Comparable](left: list[list[T]], right: list[list[T]]) -> list[list[T]]:
3945
"""
4046
>>> merge([[1, 6], [9, 10]], [[2, 3], [4, 5], [7, 8]])
4147
[[1, 6], [2, 3], [4, 5], [7, 8], [9, 10]]
@@ -49,7 +55,7 @@ def merge(left, right):
4955
return result + left + right
5056

5157

52-
def sortlist_2d(list_2d):
58+
def sortlist_2d[T: Comparable](list_2d: list[list[T]]) -> list[list[T]]:
5359
"""
5460
>>> sortlist_2d([[9, 10], [1, 6], [7, 8], [2, 3], [4, 5]])
5561
[[1, 6], [2, 3], [4, 5], [7, 8], [9, 10]]
@@ -61,7 +67,7 @@ def sortlist_2d(list_2d):
6167
return merge(sortlist_2d(list_2d[:middle]), sortlist_2d(list_2d[middle:]))
6268

6369

64-
def merge_insertion_sort(collection: list[int]) -> list[int]:
70+
def merge_insertion_sort[T: Comparable](collection: list[T]) -> list[T]:
6571
"""Pure implementation of merge-insertion sort algorithm in Python
6672
6773
:param collection: some mutable ordered collection with heterogeneous

‎tests/test_sorts.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
from sorts.insertion_sort import insertion_sort
3737
from sorts.intro_sort import sort as intro_sort
3838
from sorts.iterative_merge_sort import iter_merge_sort
39+
from sorts.merge_insertion_sort import merge_insertion_sort
3940
from sorts.merge_sort import merge_sort
4041
from sorts.odd_even_sort import odd_even_sort
4142
from sorts.odd_even_transposition_single_threaded import odd_even_transposition
@@ -75,6 +76,7 @@ def test_heap_sort() -> None:
7576
intro_sort,
7677
iter_merge_sort,
7778
merge,
79+
merge_insertion_sort,
7880
merge_sort,
7981
odd_even_sort,
8082
odd_even_transposition,
@@ -148,6 +150,7 @@ def test_rec_insertion_sort(case) -> None:
148150
insertion_sort,
149151
intro_sort,
150152
merge,
153+
merge_insertion_sort,
151154
merge_sort,
152155
odd_even_sort,
153156
odd_even_transposition,

0 commit comments

Comments
 (0)