Skip to content

Create adaptive_merge_sort.py #11990

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
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
69 changes: 69 additions & 0 deletions sorts/adaptive_merge_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"""
Adaptive Merge Sort implementation.
https://www.tutorialspoint.com/adaptive-merging-and-sorting-in-data-structure
"""

from typing import List

Check failure on line 6 in sorts/adaptive_merge_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP035)

sorts/adaptive_merge_sort.py:6:1: UP035 `typing.List` is deprecated, use `list` instead

Check failure on line 6 in sorts/adaptive_merge_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (F401)

sorts/adaptive_merge_sort.py:6:20: F401 `typing.List` imported but unused


def adaptive_merge_sort(sequence: list) -> list:
"""
>>> adaptive_merge_sort([12, 11, 13, 5, 6, 7])
[5, 6, 7, 11, 12, 13]

>>> adaptive_merge_sort([4, 3, 2, 1])
[1, 2, 3, 4]

>>> adaptive_merge_sort(["apple", "zebra", "mango", "banana"])
['apple', 'banana', 'mango', 'zebra']
"""
if len(sequence) < 2:
return sequence

aux = sequence[:]
adaptive_merge_sort_recursive(sequence, aux, 0, len(sequence) - 1)
return sequence


def adaptive_merge_sort_recursive(arr: list, aux: list, low: int, high: int) -> None:
if high <= low:
return

mid = (low + high) // 2
adaptive_merge_sort_recursive(aux, arr, low, mid)
adaptive_merge_sort_recursive(aux, arr, mid + 1, high)

if arr[mid] <= arr[mid + 1]:
arr[low : high + 1] = aux[low : high + 1]
return

merge(arr, aux, low, mid, high)


def merge(arr: list, aux: list, low: int, mid: int, high: int) -> None:
i, j = low, mid + 1

for k in range(low, high + 1):
if i > mid:
aux[k] = arr[j]
j += 1
elif j > high:
aux[k] = arr[i]
i += 1
elif arr[j] < arr[i]:
aux[k] = arr[j]
j += 1
else:
aux[k] = arr[i]
i += 1


if __name__ == "__main__":
assert adaptive_merge_sort([12, 11, 13, 5, 6, 7]) == [5, 6, 7, 11, 12, 13]
assert adaptive_merge_sort([4, 3, 2, 1]) == [1, 2, 3, 4]
assert adaptive_merge_sort(["apple", "zebra", "mango", "banana"]) == [
"apple",
"banana",
"mango",
"zebra",
]
Loading