Files
Python/sorts/adaptive_merge_sort.py
Ferbiya Peterandpre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> a85209fec1 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>
2026-09-18 02:44:50 +02:00

57 lines
1.3 KiB
Python

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[:]
adaptive_merge_sort_helper(sequence, aux, 0, len(sequence) - 1)
return sequence
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
adaptive_merge_sort_helper(aux, array, low, mid)
adaptive_merge_sort_helper(aux, array, mid + 1, high)
if not array[mid + 1] < array[mid]:
array[low : high + 1] = aux[low : high + 1]
return
merge(array, aux, low, mid, high)
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:
aux[k] = array[j]
j += 1
else:
aux[k] = array[i]
i += 1
elif not array[j] < array[i]:
aux[k] = array[i]
i += 1
else:
aux[k] = array[j]
j += 1
for k in range(low, high + 1):
array[k] = aux[k]