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 29f60d1

Browse files
authoredOct 16, 2024··
Update adaptive_merge_sort.py
1 parent b82503e commit 29f60d1

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
 

‎sorts/adaptive_merge_sort.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,61 @@
1+
def adaptive_merge_sort(sequence: list) -> list:
2+
"""
3+
Sorts a list using the Adaptive Merge Sort algorithm.
4+
5+
>>> adaptive_merge_sort([4, 3, 1, 2])
6+
Initial sequence: [4, 3, 1, 2]
7+
Sorting: array[0:2] and array[2:4]
8+
Sorting: array[0:1] and array[1:2]
9+
Merging: array[0:1] and array[1:2]
10+
After merge: [3, 4]
11+
Sorting: array[2:3] and array[3:4]
12+
Skipping merge as array[2] <= array[3]
13+
Merging: array[0:2] and array[2:4]
14+
After merge: [1, 2, 3, 4]
15+
Sorted sequence: [1, 2, 3, 4]
16+
[1, 2, 3, 4]
17+
"""
18+
if len(sequence) < 2:
19+
return sequence
20+
21+
aux = sequence[:]
22+
print(f"Initial sequence: {sequence}")
23+
adaptive_merge_sort_helper(sequence, aux, 0, len(sequence) - 1)
24+
print(f"Sorted sequence: {sequence}")
25+
return sequence
26+
27+
28+
def adaptive_merge_sort_helper(array: list, aux: list, low: int, high: int) -> None:
29+
"""
30+
Helper function for Adaptive Merge Sort algorithm.
31+
32+
>>> adaptive_merge_sort_helper([4, 3, 1, 2], [4, 3, 1, 2], 0, 3)
33+
Sorting: array[0:2] and array[2:4]
34+
Sorting: array[0:1] and array[1:2]
35+
Merging: array[0:1] and array[1:2]
36+
After merge: [3, 4]
37+
Sorting: array[2:3] and array[3:4]
38+
Skipping merge as array[2] <= array[3]
39+
Merging: array[0:2] and array[2:4]
40+
After merge: [1, 2, 3, 4]
41+
"""
42+
if high <= low:
43+
return
44+
45+
mid = (low + high) // 2
46+
print(f"Sorting: array[{low}:{mid + 1}] and array[{mid + 1}:{high + 1}]")
47+
48+
adaptive_merge_sort_helper(aux, array, low, mid)
49+
adaptive_merge_sort_helper(aux, array, mid + 1, high)
50+
51+
if array[mid] <= array[mid + 1]:
52+
print(f"Skipping merge as array[{mid}] <= array[{mid + 1}]")
53+
array[low:high + 1] = aux[low:high + 1]
54+
return
55+
56+
merge(array, aux, low, mid, high)
57+
58+
159
def merge(array: list, aux: list, low: int, mid: int, high: int) -> None:
260
"""
361
Merges two sorted subarrays of the main array.
@@ -27,3 +85,8 @@ def merge(array: list, aux: list, low: int, mid: int, high: int) -> None:
2785
array[k] = aux[k]
2886

2987
print(f"After merge: {array[low:high + 1]}")
88+
89+
90+
# Example usage
91+
if __name__ == "__main__":
92+
print(adaptive_merge_sort([4, 3, 1, 2]))

0 commit comments

Comments
 (0)
Please sign in to comment.