mirror of
https://github.com/TheAlgorithms/Python.git
synced 2026-09-28 13:33:11 +08:00
* 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>
57 lines
1.3 KiB
Python
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]
|