Refactor adaptive_merge_sort for type safety with Protocol (#15367)

* Refactor adaptive_merge_sort for type safety with Protocol

* Add doctests for adaptive_merge_sort

Removed print statements for initial sequence, sorted sequence, sorting steps, and after merge.

* Fix quotes in adaptive_merge_sort docstring examples

Updated docstring examples to use consistent quotes.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Remove doctests incompatible with parallel test runner

Removed docstring examples from adaptive_merge_sort function.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix whitespace in adaptive_merge_sort

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
Ferbiya Peter
2026-09-18 02:44:50 +02:00
committed by GitHub
co-authored by pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
parent 92fa11bd39
commit a85209fec1
+17 -18
View File
@@ -1,36 +1,42 @@
def adaptive_merge_sort(sequence: list) -> list:
from typing import Protocol
class Comparable(Protocol):
def __lt__(self, other: object, /) -> bool: ...
def adaptive_merge_sort[T: Comparable](sequence: list[T]) -> list[T]:
if len(sequence) < 2:
return sequence
aux = sequence[:]
print(f"Initial sequence: {sequence}")
adaptive_merge_sort_helper(sequence, aux, 0, len(sequence) - 1)
print(f"Sorted sequence: {sequence}")
return sequence
def adaptive_merge_sort_helper(array: list, aux: list, low: int, high: int) -> None:
def adaptive_merge_sort_helper[T: Comparable](
array: list[T], aux: list[T], low: int, high: int
) -> None:
if high <= low:
return
mid = (low + high) // 2
print(f"Sorting: array[{low}:{mid + 1}] and array[{mid + 1}:{high + 1}]")
adaptive_merge_sort_helper(aux, array, low, mid)
adaptive_merge_sort_helper(aux, array, mid + 1, high)
if array[mid] <= array[mid + 1]:
print(f"Skipping merge as array[{mid}] <= array[{mid + 1}]")
if not array[mid + 1] < array[mid]:
array[low : high + 1] = aux[low : high + 1]
return
merge(array, aux, low, mid, high)
def merge(array: list, aux: list, low: int, mid: int, high: int) -> None:
print(f"Merging: array[{low}:{mid + 1}] and array[{mid + 1}:{high + 1}]")
def merge[T: Comparable](
array: list[T], aux: list[T], low: int, mid: int, high: int
) -> None:
i, j = low, mid + 1
for k in range(low, high + 1):
if i > mid or j > high:
if i > mid:
@@ -39,7 +45,7 @@ def merge(array: list, aux: list, low: int, mid: int, high: int) -> None:
else:
aux[k] = array[i]
i += 1
elif array[i] <= array[j]:
elif not array[j] < array[i]:
aux[k] = array[i]
i += 1
else:
@@ -48,10 +54,3 @@ 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]}")
# Example usage
if __name__ == "__main__":
print(adaptive_merge_sort([4, 3, 1, 2]))