Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit d12949d

Browse files
authoredOct 11, 2024··
Create adaptive_merge_sort.py
1 parent e9e7c96 commit d12949d

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
 

‎sorts/adaptive_merge_sort.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""
2+
Adaptive Merge Sort implementation.
3+
https://www.tutorialspoint.com/adaptive-merging-and-sorting-in-data-structure
4+
"""
5+
6+
from typing import List
7+
8+
def adaptive_merge_sort(sequence: list) -> list:
9+
"""
10+
>>> adaptive_merge_sort([12, 11, 13, 5, 6, 7])
11+
[5, 6, 7, 11, 12, 13]
12+
13+
>>> adaptive_merge_sort([4, 3, 2, 1])
14+
[1, 2, 3, 4]
15+
16+
>>> adaptive_merge_sort(["apple", "zebra", "mango", "banana"])
17+
['apple', 'banana', 'mango', 'zebra']
18+
"""
19+
if len(sequence) < 2:
20+
return sequence
21+
22+
aux = sequence[:]
23+
adaptive_merge_sort_recursive(sequence, aux, 0, len(sequence) - 1)
24+
return sequence
25+
26+
def adaptive_merge_sort_recursive(arr: list, aux: list, low: int, high: int) -> None:
27+
if high <= low:
28+
return
29+
30+
mid = (low + high) // 2
31+
adaptive_merge_sort_recursive(aux, arr, low, mid)
32+
adaptive_merge_sort_recursive(aux, arr, mid + 1, high)
33+
34+
if arr[mid] <= arr[mid + 1]:
35+
arr[low:high + 1] = aux[low:high + 1]
36+
return
37+
38+
merge(arr, aux, low, mid, high)
39+
40+
def merge(arr: list, aux: list, low: int, mid: int, high: int) -> None:
41+
i, j = low, mid + 1
42+
43+
for k in range(low, high + 1):
44+
if i > mid:
45+
aux[k] = arr[j]
46+
j += 1
47+
elif j > high:
48+
aux[k] = arr[i]
49+
i += 1
50+
elif arr[j] < arr[i]:
51+
aux[k] = arr[j]
52+
j += 1
53+
else:
54+
aux[k] = arr[i]
55+
i += 1
56+
57+
58+
if __name__ == "__main__":
59+
assert adaptive_merge_sort([12, 11, 13, 5, 6, 7]) == [5, 6, 7, 11, 12, 13]
60+
assert adaptive_merge_sort([4, 3, 2, 1]) == [1, 2, 3, 4]
61+
assert adaptive_merge_sort(["apple", "zebra", "mango", "banana"]) == ['apple', 'banana', 'mango', 'zebra']

0 commit comments

Comments
 (0)
Please sign in to comment.